Reputation: 3
I have many images which have bounding boxes all drawn in the same color and are all rectangles. How can I extract the image inside the bounding box? There are similar questions but none of those solutions work properly. Can anybody help please? The below image is an example. I would like to use python Opencv to do this.
EDIT------------------------------------------------------------------
This code works perfectly for all the images. It's based on answer from sipho
img = cv2.imread(img_url)
hsv_min = np.array([0, 250, 100],np.uint8)
hsv_max = np.array([10, 255, 255],np.uint8)
hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
frame_threshed = cv2.inRange(hsv_img, hsv_min, hsv_max)
# Perform morphology
se = np.ones((1,1), dtype='uint8')
image_close = cv2.morphologyEx(frame_threshed, cv2.MORPH_CLOSE, se)
cv2.imshow(image_close)
cv2.waitkey(0)
# detect contours on the morphed image
ret,thresh = cv2.threshold(image_close,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areaArray = []
for i, c in enumerate(contours):
area = cv2.contourArea(c)
areaArray.append(area)
# Sort countours based on area
sorteddata = sorted(zip(areaArray, contours), key=lambda x: x[0], reverse=True)
# find the nth largest contour [n-1][1], in this case 2
largestcontour = sorteddata[0][1]
# get the bounding rectangle of the contour
x, y, w, h = cv2.boundingRect(largestcontour)
cropped_img = img[y+3:y+h-3,x+3:x+w-3]
cv2.imshow('cropped', cropped_img)
cv2.waitkey(0)
Upvotes: 0
Views: 2858
Reputation: 188
You could try the following:
If you are still completely stumped, view this example code
Upvotes: 1