首页 > 解决方案 > 使用 OpenCV 识别多个矩形并在它们周围绘制边界框

问题描述

我试图在图像中找到的两个矩形周围绘制一个边界框,但不包括弯曲的“噪音”

在此处输入图像描述

在此处输入图像描述

我尝试了多种方法,包括霍夫线变换和尝试提取坐标,但无济于事。我的方法似乎太武断了,我试图找到真正的矩形和帧顶部的噪点之间的黑色空间,但无法找到适合它的可靠通用算法。

标签: pythonopencv

解决方案


这不是那么简单,您可以尝试隔离非常可区分的垂直线,扩大/侵蚀以使矩形成为矩形,并找到剩下的轮廓并相应地过滤它们......代码将看起来像:

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

结果是:

在此处输入图像描述

在此处输入图像描述

如果它不适用于其他图像,请尝试调整参数。


推荐阅读