从装箱的表单域图像中提取手写字符

时间:2019-12-26 22:20:39

标签: python opencv image-processing computer-vision image-segmentation

我正在尝试从字段框中提取手写字符

enter image description here

我想要的输出将是删除了框的字符段。到目前为止,我尝试过按区域定义轮廓并进行过滤,但是效果不佳。

Word: [word, wordset_id]
Meaning: [word, meaning_id, def, example, speech_part
Synonym: [word, synonym_word]

1 个答案:

答案 0 :(得分:0)

这是一种简单的方法:

  1. 获取二进制图像。我们加载图像,使用imutils.resize()进行放大,转换为灰度,然后执行Otsu的阈值获取二进制图像

  2. 删除水平线。我们创建一个水平内核,然后执行形态学开放,并使用cv2.drawContours

  3. 删除水平线。
  4. 删除垂直线。我们创建一个垂直内核,然后执行形态学开放,并使用cv2.drawContours

  5. 删除垂直线。

这是每个步骤的可视化:

二进制图片

检测到的行/框以绿色突出显示

结果

代码

import cv2
import numpy as np
import imutils

# Load image, enlarge, convert to grayscale, Otsu's threshold
image = cv2.imread('1.png')
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,1))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 5)

# Remove vertical
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,25))
detect_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 5)

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()