0
contours, hierarchy = cv2.findContours(opening,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)


idx =0 
for cnt in contours:
    if cv2.contourArea(cnt) >3000:
        idx += 1
        x,y,w,h = cv2.boundingRect(cnt)
        roi=img[y:y+h,x:x+w]
        cv2.imwrite(str(idx) + ".jpg", roi)
        cv2.rectangle(img,(x,y),(x+w,y+h),(200,0,0),2)

It works, but the crop contours saved randomly. I need the crop image saved respected to X value from low to high.

loay
  • 19
  • 5

1 Answers1

0

Contours are generated in (approximately) increasing Y order - so the X coordinate of the bounding box would be pseudo-random (depending only on the image)

You would have to accumulate the BoundingRects, sort them by x and then make the regions.

see How to sort (list/tuple) of lists/tuples?

Community
  • 1
  • 1
Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
  • did you mean make the following – loay Apr 15 '15 at 20:24
  • did you mean make the following – loay Apr 15 '15 at 20:26
  • import numpy as np import cv2 im = cv2.imread('Selection_063.png',0) (thresh, im_bw)=cv2.threshold(im , 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(im_bw,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) idx =0 for cnt in contours: if cv2.contourArea(cnt)>200: idx += 1 x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(im,(x,y),(x+w,y+h),(200,0,0),2) roi=im[y:y+h,x:x+w] (thresh, im_bw)=cv2.threshold(roi , 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) cv2.imwrite(str(idx) + ".jpg", im_bw) – loay Apr 15 '15 at 20:26