我想在大于某个阈值的区域的每个闭合轮廓周围绘制一个边界框,而不仅仅是最大的轮廓。我该怎么做呢? 到目前为止,这是我尝试过的:
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()
关于python - 在给定大小区域轮廓周围绘制边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23398926/