python - 使用 OpenCV 识别多个矩形并在它们周围绘制边界框
问题描述
我试图在图像中找到的两个矩形周围绘制一个边界框,但不包括弯曲的“噪音”
我尝试了多种方法,包括霍夫线变换和尝试提取坐标,但无济于事。我的方法似乎太武断了,我试图找到真正的矩形和帧顶部的噪点之间的黑色空间,但无法找到适合它的可靠通用算法。
解决方案
这不是那么简单,您可以尝试隔离非常可区分的垂直线,扩大/侵蚀以使矩形成为矩形,并找到剩下的轮廓并相应地过滤它们......代码将看起来像:
import numpy as np
import cv2
minArea = 20 * 20 # area of 20 x 20 pixels
# load image and threshold it
original = cv2.imread("a.png")
img = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
ret, thres = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY )
# Get the vertical lines
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 10))
vertical = cv2.erode(thres, verticalStructure)
vertical = cv2.dilate(vertical, verticalStructure)
# close holes to make it solid rectangle
kernel = np.ones((45,45),np.uint8)
close = cv2.morphologyEx(vertical, cv2.MORPH_CLOSE, kernel)
# get contours
im2, contours, hierarchy = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# draw the contours with area bigger than a minimum and that is almost rectangular
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
if area > (w*h*.60) and area > minArea:
original = cv2.rectangle(original, (x,y),(x+w,y+h), (0,0,255), 3)
cv2.imshow("image", original)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果是:
如果它不适用于其他图像,请尝试调整参数。
推荐阅读
- python - 散景线图:绘制大量线时如何分配颜色
- php - 我在加载索引页面时遇到问题我遇到错误,同时在 php 中使用 MVC
- c# - Unity3D Agora 视频聊天与 Ar Foundation Face Tracking
- java - 如何使用 Java 11 运行已编译的 Java 8 JavaFX 应用程序 jar?
- asp.net-core - 只有多个托管服务中的第一个正在启动
- typescript - 在打字稿项目中使用 parser5
- firebase - React Native Firebase 在一个组件中显示两个集合(需要 JOIN 查询)
- python - Spyder (4.1.5) 代码单元格功能更改高亮外观
- sql-server - 带有字符串字段的 SQL 数据仓库外部表
- python - 尝试使用 JSON 获取 Pandas 的 API 数据时出错