python - 在带有噪声边的矩形周围找到已知大小的旋转边界框

标签 python opencv

我正在尝试围绕不太完美的二值化矩形图像找到一个旋转的边界框。瑕疵总是不同的:有时它是空心的,有时里面有东西,有时其中一个边缘缺少一 block ,有时在边缘的某处有一个额外的 block ,它们总是稍微旋转一个随机的量,但大小预期边界框的形状总是几乎相同的像素绝对值。

这是我作为输入的一些示例(调整大小以更好地适应帖子):

理想情况下,我想在白色矩形的外部找到一个边界框(尽管我主要只对边缘感兴趣),如下所示:

(通过反转其中一个空心的,获得最大的连接组件,并获得强制尺寸的旋转方向找到)

到目前为止,我已经尝试只获取一个 rotatedrect 并在之后强制一个形状,这几乎适用于所有情况,除非沿着其中一个边缘有一个额外的 block 。我已经尝试获取连接的组件以隔离它的部分并在它们周围设置边界框,只要它们是空心的,它就适用于所有情况。我试过扩大和侵 eclipse 图像,获取轮廓和霍夫线以尝试仅找到四个角点,但我也没有运气。我也在网上寻找任何有用的东西但无济于事。

如有任何帮助或想法,我们将不胜感激。

最佳答案

我的解决方案包括两部分:

  1. 通过找到最大的连通分量找到大白色矩形的(直立)边界框,填充其中的所有孔,找到外部垂直线和水平线(Hough),通过取最小/最大 x/y 得到边界框坐标。
  2. 将给定大小的(填充的)矩形与第 1 步中不同角度的边界框中心匹配,打印最佳匹配结果。

以下是演示此方法的简单程序。开头的参数(文件名、已知矩形的大小、角度搜索范围)通常会从命令行传入。

    import cv2
    import numpy as np

    # arguments
    file = '1.png'
    w0, h0 = 425, 630  # size of known rectangle
    ang_range = 1      # posible range (+/-) of angle in degrees

    # read image
    img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
    h, w = img.shape

    # find biggest connceted components
    nb_components, output, stats, _ = cv2.connectedComponentsWithStats(img, connectivity=4)
    sizes = stats[:, -1]
    max_label, max_size = 1, sizes[1]
    for i in range(2, nb_components):
        if sizes[i] > max_size:
            max_label = i
            max_size = sizes[i]
    img2 = np.zeros(img.shape, np.uint8)
    img2[output == max_label] = 128

    # fill holes
    contours, _ = cv2.findContours(img2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    for contour in contours:
        cv2.drawContours(img2, [contour], 0, 128, -1)

    # find lines
    edges = cv2.Canny(img2, 50, 150, apertureSize = 3)
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 40)

    # find bounding lines
    xmax = ymax = 0
    xmin, ymin = w-1, h-1
    for i in range(lines.shape[0]):
        x1 = lines[i][0][0]
        y1 = lines[i][0][1]
        x2 = lines[i][0][2]
        y2 = lines[i][0][3]
        cv2.line(img2, (x1,y1), (x2,y2), 255, 2, cv2.LINE_AA)
        if abs(x1-x2) < abs(y1-y2):
            # vertical line
            xmin = min(xmin,x1,x2)
            xmax = max(xmax,x1,x2)
        else:
            # horizcontal line
            ymin = min(ymin,y1,y2)
            ymax = max(ymax,y1,y2)
    cv2.rectangle(img2, (xmin,ymin), (xmax,ymax), 255, 1, cv2.LINE_AA)
    cv2.imwrite(file.replace('.png', '_intermediate.png'), img2)

    # rectangle of known size centered at bounding box
    xc = (xmax + xmin) / 2
    yc = (ymax + ymin) / 2
    box = np.zeros(img.shape, np.uint8)
    box[int(yc-h0/2):int(yc+h0/2), int(xc-w0/2):int(xc+w0/2)] = 255

    # find best match of this rectangle at different angles
    smax = angmax = 0
    for ang in np.linspace(-ang_range, ang_range, 20):
       rm = cv2.getRotationMatrix2D((xc,yc), ang, 1)
       rotbox = cv2.warpAffine(box, rm, (w,h))
       s = cv2.countNonZero(cv2.bitwise_and(rotbox, img))
       if s > smax:
           smax = s
           angmax = ang

    # output and visualize result
    def draw_rotated_rect(img, size, center, angle, color, thickness):
        rm = cv2.getRotationMatrix2D(center, angle, 1)
        p0 = np.dot(rm,(xc-w0/2, yc-h0/2,1))
        p1 = np.dot(rm,(xc-w0/2, yc+h0/2,1))
        p2 = np.dot(rm,(xc+w0/2, yc+h0/2,1))
        p3 = np.dot(rm,(xc+w0/2, yc-h0/2,1))
        pnts = np.int32(np.vstack([p0,p1,p2,p3]) + 0.5).reshape(-1,4,2)
        cv2.polylines(img, pnts, True, color, thickness, cv2.LINE_AA)
        print(f'{file}: edges {pnts[0].tolist()}, angle = {angle:.2f}°')

    res = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    draw_rotated_rect(res, (w0,h0), (xc,yc), angmax, (0,255,0), 2)
    cv2.imwrite(file.replace('.png', '_result.png'), res)

显示其工作原理的中间结果(灰色 = 填充的最大连通分量,粗白线 = 霍夫线,细白色矩形 = 直立边界框):
(要查看全尺寸图片,请单击它们,然后删除文件扩展名前的最后一个 m)

intermediate 1 intermediate 2 intermediate 3 intermediate 4

结果可视化(绿色 = 已知大小的旋转矩形):

final 1 final 2 final 3 final 4

结果(最终应该被clamp到[0,image size],-1是由于 float 旋转):

1.png: edges [[17, -1], [17, 629], [442, 629], [442, -1]], angle = 0.00°
2.png: edges [[7, 18], [9, 648], [434, 646], [432, 16]], angle = 0.26°
3.png: edges [[38, 25], [36, 655], [461, 657], [463, 27]], angle = -0.26°
4.png: edges [[36, 14], [28, 644], [453, 650], [461, 20]], angle = -0.79°

正如我们在图 3 中看到的,匹配并不完美。这可能是由于示例图像被缩小到略有不同的大小,当然我不知道已知矩形的大小,所以我只是为演示假设了一个合适的值。
如果真实数据也出现这种情况,您可能不仅需要改变角度以找到最佳匹配,而且还需要将匹配框向上/向下和向右/向左移动几个像素。例如参见 Dawson-Howe: A Practical Introduction to Computer Vision with OpenCV 的第 8.1 节了解更多详情。

关于python - 在带有噪声边的矩形周围找到已知大小的旋转边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57309118/

相关文章:

opencv - 统一距离度量用于 OpenCV 特征匹配的不同实现?

c++ - 在 Windows 7 上使用 CMake 安装 OpenCV 3.1.0,opencv_ffmpeg.dll 无效哈希

没有 time.sleep() 的 Python 循环延迟

python - 如何在 python 中测试一个空的 Redis 键

python - 使用 Boto 轮询停止或启动 EC2 实例

python - 从维基数据中提取 RDF 三元组

c++ - 在 C++ 中保存为 Flash

python - 从 cv2.HoughLines 获得 miximum 票数的 rho 和 theta

python - 如何计算最小长度的矩形数?

python - Django Rest框架serializer.save()返回 "Invalid data. Expected a dictionary, but got group"