Home > Net >  How to overlay multiple images onto certain original images using python
How to overlay multiple images onto certain original images using python

Time:11-23

I am trying to create a program in which I should be able to overlay one image over another base image using python and opencv and store the output image in an other folder . I am using opencv to achieve this however the code I have written is not giving the desired result.

import cv2
from os import listdir
from os.path import isfile, join
import numpy as np

path_wf = 'wf_flare'
path_fr = 'captured_flare'

files_wf = [ f for f in listdir(path_wf) if isfile(join(path_wf,f))]
files_fr = [ fl for fl in listdir(path_fr) if isfile(join(path_fr,fl))]

img_wf = np.empty(len(files_wf), dtype = object)
img_fr = np.empty(len(files_fr), dtype = object)
img = np.empty(len(files_wf), dtype = object)
k = 0
for n in range(0, len(files_wf)):
    img_wf[n] = cv2.imread(join(path_wf, files_wf[n]))
    img_fr[k] = cv2.imread(join(path_fr, files_fr[k]))
    print("Done Reading" str(n))
    img_wf[n] = cv2.resize(img_wf[n], (1024,1024),interpolation = cv2.INTER_AREA)

    

    img[n] = 0.4*img_fr[k]   img_wf[n]

    fn = listdir(path_wf)
    name = 'C:\Flare\flare_img' str(fn[n])
    print('Creating...'  name   str(n 10991))
    cv2.imwrite(name,img[n])
    k  = 1
    if(k%255 == 0):
        k = 0
    else:
        continue

the folder organization is pasted below: enter image description here

enter image description here

enter image description here

I want the output images to come here:

enter image description here

CodePudding user response:

There are two issues in the following line:

name = 'C:\Flare\flare_img' str(fn[n])
  1. In Python, special characters in strings are escaped with backslashes. Some examples are \n (newline), \t (tab), \f (form feed), etc. In your case, the \f is a special character that leads to a malformed path. One way to fix this is to use raw strings by adding an r before the first quote:
'C:\Flare\flare_img'
Out[12]: 'C:\\Flare\x0clare_img'

r'C:\Flare\flare_img'
Out[13]: 'C:\\Flare\\flare_img'
  1. Do not just concatenate strings when you create filesystem paths. Sooner or later you end up misplacing a path separator. In this case, it is missing because fn[n] does not start with one. Let's say that fn[n] = "spam.png". Then assuming you do
name = r'C:\Flare\flare_img' str(fn[n])

your value for name will be

C:\\Flare\\flare_imgspam.png

which is not what you intended.

Use os.path.join or the modern pathlib.Path as previously suggested. It is also redundant to wrap fn[n] in the str function because os.listdir already returns a list of strings.

Documentation: Python Strings

  • Related