How to Mask an image using Numpy/OpenCV?


I am detecting wheels with a deep learning algorithm. The algorithm gives me the coordinates of those rectangles. I want to keep data that is in the rectangles of the image. I created rectangles as a mask of the area I want to keep.

Here is the output of my system

I read my image

im = cv2.imread(filename)

I created the rectangles with:

height,width,depth = im.shape

How can I mask out the data outside of the rectangle from the original image? and keep those rectangles?

Edited: I wrote this code and it only gives me one wheel. How can I have multiple masks and get all the wheels?

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

# Draw a bounding box.
# Draw a white, filled rectangle on the mask image
             pt1=(left, top), pt2=(right, bottom),
             color=(255, 255, 255),

# Apply the mask and display the result
maskedImg = cv.bitwise_and(src1=frame, src2=mask)

cv.namedWindow(winname="masked image", flags=cv.WINDOW_NORMAL)
cv.imshow(winname="masked image", mat=maskedImg)


Posted 2019-07-21T01:59:07.673

Reputation: 31

Question was closed 2020-06-02T22:38:59.247

You want to keep only wheels image, rest everything you want to mask ? – Daemon – 2019-07-21T09:09:21.387

yes, I want to keep the wheels – programmer – 2019-07-21T17:35:40.313

Programming issues are off-topic here. Please, read for more details and to understand which questions are on-topic here. If you have a programming issue, the best place to ask your question is Stack Overflow.

– nbro – 2020-06-02T22:38:55.930



You can use cv2.bitwise_and and pass rectangle as a mask.

im = cv2.imread(filename)
height,width,depth = im.shape

masked_data = cv2.bitwise_and(im, im, mask=rectangle)

cv2.imshow("masked_data", masked_data)


Posted 2019-07-21T01:59:07.673

Reputation: 111

I can only draw one mask for one wheel, how can I draw multiple masks? since I have multiple wheels in the image – programmer – 2019-07-21T17:35:12.577

@john You have coordinates of all 5 wheels right ? run a for loop on cv2.bitwise_and by passing one rectangle at a time. May not be the efficient but it will work for you. – Daemon – 2019-07-21T17:52:23.323

could you please edit the code and put a loop. I tried a lot, mine does not work, unfortunately – programmer – 2019-07-21T18:24:20.450