0

I plotted bounding box using the cv2.rectangle method by finding Contours. Now i want to crop each bounding box.

I tried slicing method to crop the images which didn't provide me the desired result. It cropped the regions that do not have any bounding box in it.

#Plotting rectangular box
ret,thresh = cv2.threshold(dilation, 127,255,0)
image, contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE )

for c in contours:
    rect = cv2.boundingRect(c)
    if rect[2] < 100 or rect[3] < 100 : continue
    print (cv2.contourArea(c))
    x,y,w,h = rect

    crop_img = img[x:x+w, y:y+h] #Cropping
    cv2.imwrite("Cropped/"+str(enumerate(c))+".jpg", crop_img)

    cv2.rectangle(im_new,(x,y),(x+w,y+h),(0,255,0),2)

cv2.imwrite('sample_res_inner.jpg',im_new)
cv2.waitKey()  
cv2.destroyAllWindows()

What changes can I make to the code to yield the desired result?

DGS
  • 475
  • 1
  • 4
  • 16

1 Answers1

0

As Piglet says, numpy arrays are indexed with y then x. So simply swapping these will do the trick.

Andreas
  • 455
  • 3
  • 7