python - 寻找特定区域的轮廓

标签 python opencv computer-vision

我在查找表中特定列的轮廓时遇到问题。使用 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)

这是我正在处理的图像:

这就是我想在其上绘制边界框的内容。仅那部分

enter image description here

现在这就是我实际得到的。

enter image description here

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

最佳答案

您这里有两个问题:

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

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

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

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

enter image description here

关于python - 寻找特定区域的轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67812373/

相关文章:

python - 使用 python 查找视频中的图像

python-3.x - 如何在python中使用spotify的annoy库?

python - 点积两个 4D Numpy 数组

python - 我正在尝试使用 Python OpenCV 将下表中的黑色单元格替换为另一个图像。我怎样才能做到这一点?

python - 如何在OpenCV中构造二值图像的水平投影

android - 如何在图像中选择正确的矩形?

c++ - 在 C++ 中读取 kinect 深度文件

Python 脚本未在新行中写入结果 - 新手

python - 如何将 Pandas Dataframe MultiIndex 行旋转到 MultiIndex 列中?

python - 屏蔽 pandas DataFrame 的下三角部分