0

I have three different folders m1, m2, and m3. The 'm1' folder contains images of the format image(i)_m1.png (where i =1 to N), 'm2' folder contains images of the format image(i)_m2.png, and 'm3' folder contains images of the format image(i)_m3.png. I want to merge these images using cv2.merge like this:(cv2.merge((image1_m1, image1_m2, image1_m3)) and it continues for N times and get stored in a different folder than contains 'N' merged images of the format image(i)_merged.png.

import pandas as pd
import cv2
import numpy as np
import glob
import os

filenames1 = glob.glob("data_folder/m1/*.png")
filenames1.sort()
filenames2 = glob.glob("data_folder/m2/*.png")
filenames2.sort()
filenames3 = glob.glob("data_folder/m3/*.png")
filenames3.sort()


for f1 in filenames1:
    for f2 in filenames2:
        for f3 in filenames3:
            img1 = cv2.imread(f1)
            img2 = cv2.imread(f2)
            img3 = cv2.imread(f3)
            img_m1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            img_m2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
            img_m3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
            img_rgb = cv2.merge((img_m1, img_m2, img_m3))
            cv2.imwrite("data_folder/merge/img_name.png", img_rgb)
shiva
  • 1,177
  • 2
  • 14
  • 31
  • 1
    Do you have a specific question? Please see [ask], [help/on-topic]. – AMC Jun 30 '20 at 00:32
  • Rather than load each image as 3 channels of BGR data and then make a 4th channel of greyscale data, you could use 1/4 of the RAM and directly load each image as greyscale with the appropriate flag to `cv2.imread()`. Your code would be shorter too. – Mark Setchell Jun 30 '20 at 13:11

1 Answers1

1

Your question is not complete. I assume you have a problem with for loop. You might replace the nested for loops with this:

for f1,f2,f3 in zip(filenames1,filenames2,filenames3):
Sdhir
  • 131
  • 4
  • Thanks. It worked. I also modified the final write statement to prevent image overwriting. – shiva Jun 30 '20 at 23:24