Search code examples
pythonopencvimage-masking

Masking many images from two different path opencv


Hello stackoverflow people:) I'm trying to masking many image from two different path, but I don't have an idea to do that. This an example for just two images and what I've do so far

image = cv.imread('Dataset/IDRiD_02.jpg', cv.IMREAD_COLOR)
od = cv.imread('od/IDRiD_02_OD.jpg', cv.IMREAD_GRAYSCALE)
mask = od
other = cv.bitwise_not(mask)
masking =  cv.bitwise_and(image, image, mask=other)
cv.imwrite('Output/masking/' + 'masking.jpg', masking)

Input is IDRiD_02.jpg and IDRiD_02_OD.jpg then Output is masking.jpg

Then I want to do the same but with many images

import cv2 as cv
import numpy as np
import os
import glob
import os.path

od_images = [] 

for directory_path in glob.glob("od/"):
    for mask_path in glob.glob(os.path.join(directory_path, "*.jpg")):
        mask = cv.imread(mask_path, cv.IMREAD_GRAYSCALE)
        od_images.append(mask)       
od_images = np.array(od_images)

path = "Dataset/*.jpg"

for file in glob.glob(path):
        
    #read image
    image = cv.imread(file, cv.IMREAD_COLOR)
    
    # e.g. MyPhoto.jpg
    basename = os.path.basename(file)
    # e.g. MyPhoto
    name = os.path.splitext(basename)[0]
    
    mask = cv.bitwise_not(od_images)
    
    masking =  cv.bitwise_and(image, image, mask = mask)
    
    cv.imwrite('Output/masking/' + name + '_masking.jpg', masking)

but then after I run the code, I'm getting the following error message

masking =  cv.bitwise_and(image, image, mask = mask)

error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\core\src\arithm.cpp:230: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'

anyone can understand and help me? Thank you before:)


Solution

  • Hope it will work for you !

    import cv2 as cv
    import os
    
    img_path = r"image_folder_path"
    od_images = r"od_img_folder_path"
    for img,od in zip(os.listdir(img_path), os.listdir(od_images)):
    
        image = cv.imread(img_path+"\\"+img, cv.IMREAD_COLOR)
        od = cv.imread(od_images+"\\"+od, cv.IMREAD_GRAYSCALE)
    
        other = cv.bitwise_not(od)
        res =  cv.bitwise_and(image, image, mask=other)
    
         cv.imwrite('Output/masking/' +img+ '_masking.jpg', res)