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

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

最佳答案

请记住,您的缩进级别在 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/

相关文章:

python - 导入错误: No module named SOAPpy

python - 如何使用 lxml 抓取 XML 文档的特定部分?

python - 在 Pandas 中以均值转换组的更快方法

python - Wget 和 Python 下载管理器?

python - Windows 上的 asyncio create_subprocess_shell python 3.7

c++ - 在 OpenCV、C++ 中创建方形晕影

java - 通过查找表更改数据

c++ - 采用 OpenCV Mat<double> 并转换为 12 位值的数组。

python - 与 numpy.unwrap 相反

python - 如何在没有循环的情况下使用 numpy.lexsort