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
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
cv.rectangle(img=mask,
             pt1=(left, top), pt2=(right, bottom),
             color=(255, 255, 255),
             thickness=-1)


# 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)
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)

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

cv2.imshow("masked_data", masked_data)
cv2.waitKey(0)