Search code examples
pythonnumpyopencvimage-processingmask

I want to mask multiple Image horizontally


I have few Journal pages images where there are two columns I want to mask one column white without a changing the dimension.which means the output image should have same dimensions as input image even though there is one column.

I was able to mask image but the mask part is coming black which I want as white.

import cv2

import numpy as np

# Load the original image

image = cv2.imread(filename = "D:\output_final_word5\image1.jpg")

# Create the basic black image 

mask = np.zeros(shape = image.shape, dtype = "uint8")

# Draw a white, filled rectangle on the mask image

cv2.rectangle(img = mask, pt1 = (0, 0), pt2 = (795, 3000), color = (255, 255, 

255), thickness = -1)

# Apply the mask and display the result

maskedImg = cv2.bitwise_and(src1 = image, src2 = mask)

#cv2.namedWindow(winname = "masked image", flags = cv2.WINDOW_NORMAL)

cv2.imshow("masked image",maskedImg)

cv2.waitKey(delay = 0)

cv2.imwrite("D:\Test_Mask.jpg",maskedImg)

My final objective is to read a folder where are several Journal pages In which need to be saved by masking first one column and then another column without affecting the dimension of Input image and mask part should be white. Below are Input Image Attached...

Input_Image1

Input_Image2

And Output Should be like this....

Output_Image1

Output_Image2


Solution

  • You don't need mask to draw rectangle. You can draw it directly on image.

    You can also use image.copy() to create second image with other column

    BTW: if 795 is in the middle of width then you can use image.shape to get its (height,width) and use width//2 instead of 795 so it will work with images which have different widths. But if 795 is not ideally in the middle then use half_width = 795

    import cv2
    
    image_1 = cv2.imread('image.jpg')
    image_2 = image_1.copy()
    
    height, width, depth = image_1.shape # it gives `height,width`, not `width,height`
    half_width = width//2
    #half_width = 795
    
    cv2.rectangle(img=image_1, pt1=(0, 0), pt2=(half_width, height), color=(255, 255, 255), thickness=-1)
    cv2.rectangle(img=image_2, pt1=(half_width, 0), pt2=(width, height), color=(255, 255, 255), thickness=-1)
    
    cv2.imwrite("image_1.jpg", image_1)
    cv2.imwrite("image_2.jpg", image_2)
    
    cv2.imshow("image 1", image_1)
    cv2.imshow("image 2", image_2)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()