在给定大小的区域轮廓周围绘制边界框

时间:2014-04-30 22:12:30

标签: python opencv numpy

我想在一个大于某个阈值的区域的每个闭合轮廓周围绘制一个边界框,而不仅仅是最大的轮廓。我该怎么做呢? 到目前为止,这是我尝试过的:

contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
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 = cv2.boundingRect(c)
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(im,'Moth Detected',(x+w+10,y+h),0,0.3,(0,255,0))
cv2.imshow("Show",im)
cv2.waitKey()  
cv2.destroyAllWindows()      

1 个答案:

答案 0 :(得分:11)

请记住,缩进级别在Python中很重要。同样值得注意的是,您的代码并不一定在最大轮廓周围绘制一个框,它会在contours的最后一个元素周围绘制一个框。幸运的是,修复很简单。您只需缩进对cv2.rectangle()cv2.putText()的调用,以便他们在每次循环迭代时进行评估。您还可以通过将cv2.boundingRect()扩展为rect来取消对x,y,w,h的通话。那么你的代码就是:

contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
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
    cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
    cv2.putText(im,'Moth Detected',(x+w+10,y+h),0,0.3,(0,255,0))
cv2.imshow("Show",im)
cv2.waitKey()  
cv2.destroyAllWindows()
相关问题