使用OpenCV检测图像中的盒子

时间:2018-08-13 09:04:40

标签: python opencv image-processing deep-learning computer-vision

我需要使用opencv在以下图像中找到方框。我曾尝试使用mser,但没有得到任何良好的结果。 Image for Finding Boxes

我的MSER代码:

mser = cv2.MSER_create()
img = cv2.imread('Lines.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
I = img.copy()
regions, _ = mser.detectRegions(I)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)
c=0
points=[]
for contour in hulls:
    [x, y, w, h] = cv2.boundingRect(contour)
    if w < 50 or h < 8 or w>120:
        continue
    c=c+1
    cv2.rectangle(I, (x, y), (x + w, y + h), (255, 0, 255), 0)
plt.figure(1,figsize=(100, 50))
plt.imshow(I)

MSER的结果: Result for MSER

4 个答案:

答案 0 :(得分:1)

您可以使用opencv提供的cv2.findContours()函数。您可以在here上使用他们的教程来了解更多信息。干杯。

答案 1 :(得分:1)

由于输入图像已反转,请使用“膨胀”和适当的结构元素来放大末梢区域,然后应用MSER。

答案 2 :(得分:1)

您可以设置图像阈值并反转白色和黑色像素,以便将框用黑线用白色分隔:

enter image description here

然后,您可以使用cv2.findContours()搜索轮廓,然后仅绘制符合尺寸标准的轮廓。您可以使用cv2.contourArea()获得轮廓的大小。这些轮廓就是您的盒子。干杯!

示例代码:

import cv2

img = cv2.imread('table.png')
resize = cv2.resize(img, None, fx=0.3, fy=0.3, interpolation = cv2.INTER_CUBIC)
gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,50,255,cv2.THRESH_BINARY_INV)
_, contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    size = cv2.contourArea(cnt)
    if 100 < size < 30000:
        cv2.drawContours(resize, [cnt], 0, (0,255,0), 1)

cv2.imshow('img', resize)

结果:

enter image description here

答案 3 :(得分:0)

我认为您可以使用像素图案来识别盒子。作为示例,遍历图像中的每个像素,当您获得白色像素时,然后找出x轴和y轴的下一个像素颜色。如果两个都是白色,则将该像素视为框的第一个像素。然后取x轴的下一个像素并找到y轴像素。如果是白色,则您已到达框的另一角。如果像素不是白色,则考虑下一个x轴像素。当您在拐角处时,找到下一个y轴像素,直到到达拐角处。当您位于第三个角落时,请考虑先前的x像素。然后找到先前的x像素,直到到达第四个角。然后您可以通过四个角的像素坐标保存该框。我认为这更准确。但这既耗时又复杂。但这可能是新算法。 (仅当框是直线时才有效)