2015-04-15 129 views
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) 

它的工作,但作物轮廓随机保存。 我需要将裁剪图像保存为X值从低到高。排序作物轮廓蟒蛇和opencv

回答

0

轮廓在(大约)增加Ÿ为了生成 - 所以X边框的协调将是伪随机(只取决于图像)

你将不得不积累BoundingRects,通过对它们进行排序x然后制作区域。

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

+0

您的意思是否进行以下 – loay

+0

你的意思做如下 – loay

+0

进口numpy的为NP 进口CV2 IM = cv2.imread( 'Selection_063.png',0) (脱粒, im_bw)= cv2.threshold(1M,128,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU) 轮廓,层次= cv2.findContours(im_bw,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) IDX = 0 为CNT在轮廓: \t if cv2.contourArea(cnt)> 200 : \t \t IDX + = 1 \t \t X,Y,W,H = cv2.boundingRect(CNT) \t \t cv2.rectangle(1M,(X,Y),(X + W,Y + h)时, (200,0,0),2) \t \t roi = im [y:y + h,x:x + w] \t \t(thresh,im_bw)= cv2.threshold(roi,128,255,cv2。 THRESH_BINARY | cv2.THRESH_OTSU) \t \t \t \t \t \t cv2.imwrite(STR(IDX)+ “.JPG”,im_bw) – loay