简体   繁体   中英

How to crop the images inside the bounding box from findContours

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM