Getting errors while cropping an image based on custom mask in python

Viewed 199

I have this two images:

enter image description here

enter image description here

And I want to use the white shape of the first one to crop the image like this:

enter image description here

Wihtout the blue lines and the info.

So that's what I'm trying to do:

 def find_intersection(self, mask, image):
        image = cv2.cvtColor(np.float32(image), cv2.COLOR_BGR2GRAY)
        masked = cv2.bitwise_and(mask, image, mask=mask)
        plt.imshow(masked)
        plt.show()

But I get this error:

cv2.error: OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-kh7iq4w7\opencv\modules\core\src\arithm.cpp:234: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function 'cv::binary_op'

The dimensions and channels of the picture are the same, so I don't know what's the problem.

1 Answers

There are 2 things that are flawed in your code:

  1. The two images you presented are of different sizes; (859, 1215, 3) and (857, 1211, 3).

  2. The mask keyword argument of the cv2.bitwise_and method must be a binary image, meaning it can only have 1 channel.

You ca fix the size difference by using the cv2.resize method, and the channels of the mask can be converted to 1 using the cv2.cvtColor method and the cv2.COLOR_BGR2GRAY option (or you can pass in 0 after the image file's name after reading in the mask file).

Here is how I would do it:

import cv2
import numpy as np

img = cv2.imread("ring_bg.png")
mask = cv2.imread("ring_mask.png")

h, w, _ = img.shape
mask = cv2.resize(cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY), (w, h)) # Resize image
bg = np.zeros_like(img, 'uint8') # Black background

def crop(img, bg, mask):
    fg = cv2.bitwise_or(img, img, mask=mask)            
    fg_back_inv = cv2.bitwise_or(bg, bg, mask=cv2.bitwise_not(mask))
    return cv2.bitwise_or(fg, fg_back_inv)

cv2.imshow("Image", crop(img, bg, mask))
cv2.waitKey(0)

Output:

enter image description here

Related