Home > Net >  How to merge multiple images into one image using opencv python
How to merge multiple images into one image using opencv python

Time:04-13

I am trying to merge images while iterating through a function, the function iterates through the folder get each image, now I am trying to merge all the images while iterating and merge them into one single image.

directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]
image_list=[]
images = []

def randomFile(directory):
    files_list = os.listdir(directory)
    random_num = random.choice(files_list)
    print(random_num,directory)
    img_1=cv2.imread((os.path.join(directory,random_num)))
    if img_1 is not None:
        images.append(img_1)
    files_list.remove(random_num)
    img1_g_noise = cv2.merge(images)
    return img1_g_noise

for x in directories[1:]:
    randomFile(x)
    cv2.imshow("img1_g_noise",randomFile(x))
    cv2.waitKey(0)

I am able to access all the images but not been able to merge into one single image, the list images=[] contains all the pixels of all three images

CodePudding user response:

You can try replacing img1_g_noise = cv2.merge(images) with:

img1_g_noise = cv2.cvtColor(images[0], cv2.COLOR_RGB2RGBA)
images.pop(0)

for img in images:
    img1_g_noise = cv2.addWeighted(img1_g_noise,0.5,cv2.cvtColor(img, cv2.COLOR_RGB2RGBA),0.5,0)
return cv2.cvtColor(img1_g_noise, cv2.COLOR_RGBA2RGB)

CodePudding user response:

In Python/OpenCV/Numpy, if all 4 images are the same dimensions, then, if input is img1, img2, img3, img4, the following will make an image that is a 2x2 collage of the input images.

img12 = np.hstack((img1, img2))
img34 = np.hstack((img3, img4))
result = np.vstack((img12, img34))

If the images are not the same size, then either crop or resize them to the same size.

  • Related