首页 > 解决方案 > 在特定区域查找轮廓

问题描述

我在查找表格中特定列的轮廓时遇到问题。使用 opencv 时的问题是,我必须指定在 x、y 和 w(2 个轴和宽度)上使用 if 循环在哪个区域绘制矩形,如果表格线完全水平或垂直,但如果它们'不是那么你就得不到好的结果。

我用这段代码来获取边界框:

import numpy as np
import cv2
img = r'C:\Users\lenovo\PycharmProjects\SoftOCR_Final\Filtered_images\filtered_image1.png'

table_image_contour = cv2.imread(img, 0)
table_image = cv2.imread(img)

ret, thresh_value = cv2.threshold(table_image_contour, 180, 255, cv2.THRESH_BINARY_INV)
kernel = np.ones((5, 5), np.uint8)
dilated_value = cv2.dilate(thresh_value, kernel, iterations=1)

contours, hierarchy = cv2.findContours(dilated_value, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    x, y, w, h = cv2.boundingRect(cnt)
    # bounding the
    if 2271 > x > 746 and w > 300 and y > 1285:
        table_image = cv2.rectangle(table_image, (x, y), (x + w, y + h), (0, 0, 255), 3)
        roi = table_image[y: y + h, x: x + w]

width = int(table_image.shape[1] * 20 / 100)
height = int(table_image.shape[1] * 20 / 100)
dsize = (width, height)
table_image = cv2.resize(table_image, dsize)
cv2.imshow('1', table_image)
cv2.waitKeyEx(0)

这是我正在处理的图像:

这就是我想画边界框的地方。只有那部分

在此处输入图像描述

现在这就是我真正得到的。

在此处输入图像描述

如您所见,我丢失了一些线条并在表格之外获得了边界框。

标签: pythonopencvcomputer-vision

解决方案


您在这里有两个问题:

  • 未检测到盒子(例如在 EL FIDHA 或 KONE 周围)
  • 签名被标记

第一个实际上不是问题,因为您最后的调整大小步骤是使边界框在视觉上消失。然而,它们被正确检测到,因为您可以通过删除 for 循环和行之间的所有代码来检查:

cv2.imshow('1', table_image)
cv2.waitKeyEx(0)

第二个问题可以通过检查边界框的最大 y 坐标来解决。将条件更改为if 1000 < x < 2000 and w > 300 and 1285 < y < 2600 :在示例图像上效果很好,得到以下结果:

在此处输入图像描述


推荐阅读