# 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

im = cv2.imread(filename)


I created the rectangles with:

height,width,depth = im.shape
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv2.rectangle(rectangle,(width/2,height/2),200,1,thickness=-1)


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),
thickness=-1)

# Apply the mask and display the result


• You want to keep only wheels image, rest everything you want to mask ? – Vinay Hegde Jul 21 at 9:09
• yes, I want to keep the wheels – 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
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv2.rectangle(rectangle,(width/2,height/2),200,1,thickness=-1)

cv2.waitKey(0)

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