Python 和 OpenCV - 查找表单中手写文本的轮廓和坐标

问题描述 投票:0回答:2

我有扫描文档的样本。该文件是表格(欧洲事故陈述),我想检测手写文本并在手写文本上绘制轮廓。

第一张图片是我的原始文档:

我想检测所有手写文本并在其上绘制边界框,如下所示:

我已经尝试使用 boxdetect 但没有成功 检测文档中的所有字段后,期望的结果应该是用户需要填写的所有字段的坐标,例如:

|      Name           |        Vorname     |      Telefon
|---------------------|--------------------|----------------------
|[(101, 172, 63, 12)] |[(105, 177, 69, 18)]| [(109, 182, 74, 23)]
python opencv machine-learning computer-vision ocr
2个回答
1
投票

如果表格几乎完全相同,您可以扫描一份空表格,然后从书面表格中减去空表格。然后,您可以应用阈值和其他一些处理来创建仅包含手写内容的二进制掩码,并对其应用文本检测。

这是我在几分钟内创建的东西:

代码大致如下:

import numpy as np
import cv2


def size_filter(image, minimum):
    ## Find connected components
    labels, vals = cv2.connectedComponentsWithStats(image)[1:3]
    vals = vals[1:, cv2.CC_STAT_AREA]

    new_img = np.zeros_like(labels, np.uint8)

    if vals.size == 0 or max(vals) < minimum:
        return new_img

    new_img[np.isin(labels, np.arange(len(vals))[vals >= minimum] + 1)] = 255

    return new_img

## Find the difference between the written form and the empty form
difference = np.abs(written_form.astype(np.int16)-base_form.astype(np.int16))

## Apply a threshold to the form
text_mask = np.all(difference > 100, axis=2)

## Remove Noise
text_mask = size_filter(text_mask)

我只花了几分钟的时间来完成这个工作,所以它并不完美,但是只要付出一点努力就可以实现。


0
投票

要实现在扫描文档中检测手写文本并在其周围绘制边框的任务,您可以按照以下步骤操作:

  1. 预处理:预处理扫描文档以增强文本。您可以应用二值化等技术将图像转换为二进制格式,这使得文本提取更容易。

  2. 文本检测:利用光学字符识别 (OCR) 工具或库来检测手写文本。 Tesseract OCR 是一种流行的开源 OCR 引擎,可用于此目的。

  3. 轮廓检测:OCR 之后,您可以应用轮廓检测技术来定位手写文本。您可以使用 OpenCV 或类似的库来查找文本的轮廓。

  4. 边界框:获得手写文本的轮廓后,在其周围绘制边界框。您可以使用 OpenCV 在检测到的文本区域周围绘制矩形。

  5. 字段提取:根据边界框的位置,您可以识别需要填写的字段。这可能需要一些手动配置才能将边界框映射到特定的表单字段。

这里有一个示例代码片段,可帮助您开始使用 Python 和 OpenCV 进行文本检测和边界框绘制:

import cv2

# Load the scanned document image
image = cv2.imread('your_image.png')

# Convert to grayscale for text detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Use OCR to extract text
import pytesseract
text = pytesseract.image_to_string(gray)

# Use OpenCV to find contours
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Iterate through the contours and draw bounding boxes
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

# Display the image with bounding boxes
cv2.imshow('Image with Bounding Boxes', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Extract fields based on bounding boxes
# You might need to manually map the bounding boxes to specific fields in your form

请记住根据您的具体文档和要求调整此代码。您可能需要根据扫描文档的特征微调 OCR 设置并调整轮廓检测。

© www.soinside.com 2019 - 2024. All rights reserved.