我想在大于某个阈值的区域的每个闭合轮廓周围绘制一个边界框,而不仅仅是最大的轮廓。我该怎么做?到目前为止,这就是我尝试过的:
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()
记住,您的缩进级别在Python中很重要。同样值得注意的是,您的代码不一定要在最大轮廓周围绘制一个方框,而是在contours
的最后一个元素周围绘制一一个方框。幸运的是,修复很简单。您只需要缩进对cv2.rectangle()
和cv2.putText()
的调用,以便它们在每次循环迭代中进行求值。您还可以通过将rect
扩展到x,y,w,h
来消除对cv2.boundingRect()
的调用。然后你的代码是:
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()