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)
  • $\begingroup$ You want to keep only wheels image, rest everything you want to mask ? $\endgroup$ – Vinay Hegde Jul 21 at 9:09
  • $\begingroup$ yes, I want to keep the wheels $\endgroup$ – programmer Jul 21 at 17:35

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)
  • $\begingroup$ I can only draw one mask for one wheel, how can I draw multiple masks? since I have multiple wheels in the image $\endgroup$ – programmer Jul 21 at 17:35
  • $\begingroup$ @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. $\endgroup$ – Vinay Hegde Jul 21 at 17:52
  • $\begingroup$ could you please edit the code and put a loop. I tried a lot, mine does not work, unfortunately $\endgroup$ – programmer Jul 21 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.