Python 围绕给定大小区域轮廓绘制边界框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23398926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:55:40  来源:igfitidea点击:

Drawing Bounding box around given size Area contour

pythonopencvnumpy

提问by Mohamed Elfatih

I want to draw a bounding box around each closed contour of an area larger than some threshold, not just the biggest contour. How can I go about doing this? So far this is what I have tried:

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

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()      

采纳答案by Aurelius

Remember, your indentation level matters in Python. It's also worth noting that your code doesn't necessarily draw a box around the largest contour, it draws a box around the last element of contours. Fortunately, the fix is simple. You just need to indent your calls to cv2.rectangle()and cv2.putText()so they evaluate on every loop iteration. You can also eliminate a call to cv2.boundingRect()by expanding rectinto x,y,w,h. Your code would then be:

请记住,您的缩进级别在 Python 中很重要。还值得注意的是,您的代码不一定在最大轮廓周围绘制一个框,而是在contours. 幸运的是,修复很简单。您只需要缩进您的调用cv2.rectangle()cv2.putText()以便它们在每次循环迭代中进行评估。您还可以cv2.boundingRect()通过扩展rectx,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()