使用OpenCV

时间:2019-07-01 01:32:28

标签: python opencv

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

enter image description here

enter image description here

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

1 个答案:

答案 0 :(得分:1)

这并不是一件容易的事,您可以尝试分离出非常容易区分的垂直线,通过扩张/腐蚀使矩形成为矩形,然后找到剩下的轮廓并对其进行过滤...代码如下:

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

结果是:

enter image description here

enter image description here

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