Home > other >  Merge two image folders in Python
Merge two image folders in Python

Time:10-08

[I am trying to merge all .jpg images from the training and validation set for further analysis][1]

  [1]: https://i.stack.imgur.com/KUjbz.png

train_img = glob.glob("/Users/prat/train/train2014/*.jpg")
train_img.sort()
val_img = glob.glob("/Users/prat/validation/val2014/*.jpg")
val_img.sort()

for f1 in train_img:
    for f2 in val_img:
            img1 = cv2.imread(f1)
            img2 = cv2.imread(f2)
           
            img_m1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
            img_m2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
            
            img_rgb = cv2.merge((img_m1, img_m2))
            cv2.imwrite("/Users/prat/coco_image/img_name.jpg",img_rgb)

errror : error: OpenCV(4.6.0) /Users/xperience/actions-runner/_work/opencv-python/opencv-python/opencv/modules/core/src/merge.dispatch.cpp:129: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'merge'

CodePudding user response:

It's telling you the dimensions or the depths of the two images you are trying to merge, are different, i.e. incompatible.

I suggest you use the debugger to look at them, or print them.

I think you are going to have trouble on the next line too, as saving a 2-channel image as a 3-channel RGB JPEG might be problematic.

CodePudding user response:

Thank you all, it was my first question on the stack and I am glad that I received a quick response however, I am not sure if it's logical or not but I have copied all train images to validation and it gave me desired output and I have ignored the train data.

import glob
import shutil
import os

src_dir = "/Users/prat/train/train2014/"
dst_dir = "/Users/prat/validation/val2014/"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
    shutil.copy(jpgfile, dst_dir)

Desired output acheived

  • Related