python - 光学字符识别。字符分割阶段
问题描述
我正在尝试实现 OCR 系统的其中一个阶段。字符分割阶段。代码如下所示。代码很简单:
- 正在读取图像
- 灰度图像转换
- 图像二值化
- 膨胀运算的应用
- 轮廓的选择
假设每个选定的轮廓都是一个符号。
该算法的结果并不令人满意。有时,角色很突出。有时只突出显示部分字符,有时突出显示几个字符。请帮助代码,我真的希望它能够正确突出显示字符。
更新 1.我正在尝试为不同的字体实现字符分割系统。原来不同字体的腐蚀和膨胀操作没有通用的参数
测试图像:
字符选择1的结果(字符的小部分):
完整结果(字符的所有部分):
import cv2
import numpy as np
def letters_extract(image_file):
img = cv2.imread(image_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
img_dilate = cv2.dilate(thresh, np.ones((1, 1), np.uint8), iterations=1)
# img_erode = cv2.erode(img_dilate, np.ones((3, 3), np.uint8), iterations=1)
# Get contours
contours, hierarchy = cv2.findContours(img_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
letters = []
for idx, contour in enumerate(contours):
(x, y, w, h) = cv2.boundingRect(contour)
if hierarchy[0][idx][3] == 0:
letter_crop = gray[y:y + h, x:x + w]
letters.append(letter_crop)
cv2.imwrite(r'D:\projects\proj\test\tnr\{}.png'.format(idx), letter_crop)
return letters
letters_extract(r'D:\projects\proj\test\test_tnr.png')
解决方案
运行您的代码(为调试而稍作修改),它看起来相当不错(我只更改了膨胀掩码):
import cv2
import numpy as np
import matplotlib.pyplot as plt
def letters_extract(image_file):
img = cv2.imread(image_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
plt.figure(figsize=(20, 20))
plt.imshow(thresh)
plt.show()
img_dilate = cv2.erode(thresh, np.ones((2,1), np.uint8))
plt.figure(figsize=(20, 20))
plt.imshow(img_dilate)
plt.show()
contours, hierarchy = cv2.findContours(img_dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
im_with_aabb = img.copy()
for idx, contour in enumerate(contours):
(x, y, w, h) = cv2.boundingRect(contour)
if hierarchy[0][idx][3] == 0:
color = (255, 0, 0)
thickness = 1
im_with_aabb = cv2.rectangle(im_with_aabb, (x,y), (x+w,y+h), color, thickness)
return im_with_aabb
im_with_aabb = letters_extract('test.png')
plt.figure(figsize=(20, 20))
plt.imshow(im_with_aabb)
plt.show()
但是几个字符仍然存在问题。如果您的输入图像看起来不错(不同位置的相同字符之间没有高可变性),我可以建议将每个字符作为模板进行模板匹配。
如果数据具有很高的可变性,那么您应该使用像tesseract这样的预训练 NN 。
推荐阅读
- html - 消除操作系统/浏览器添加的滚动空间
- node.js - 节点js服务器propplem
- git - GitFlow 工作流,从 UpStream Master 拉取,然后合并成什么?
- c++ - Leadtools 没有足够的可用内存
- c++ - 如何解决 C++ 中的“cppcoreguidelines-pro-type-cstyle-cast”错误?
- batch-file - 有没有办法将长而重复的“设置”命令缩小为单个命令?
- javascript - JavaScript 中的错误
- javascript - 在hackerearth中执行此问题时,将数组的元素相乘会为javascript中的大量输入提供无穷大
- python - 来自 youtube 的“如何在 Python 中创建医院管理系统”-语法错误
- javascript - 无法 postgresql db rsync 到常量 db cdb