python - 使用 python 图像处理识别材料上的 ID
问题描述
我想阅读线圈上的文字(一些 ID 包含数字)。但是 OCR 程序无法识别它。当我给出小部分时,它只能识别线性部分(3个数字)。我认为这是因为 ID 是半圆形的。我必须检测 ID,并且我正在使用带有 tesseract 库的 python 代码。我怎样才能做到这一点?谢谢。
# import the necessary packages
import numpy as np
import pytesseract
import argparse
import imutils
import cv2
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
image = cv2.imread('1.jpg')
#Cropping and having Region Of Interest
(h, w) = image.shape[:2]
ROI = image[200:450, 1100:1550]
cv2.imshow("ROI", ROI)
gray = cv2.cvtColor(ROI, cv2.COLOR_BGR2GRAY)
cv2.imshow("ROI", gray)
# threshold the image using Otsu's thresholding method
thresh = cv2.threshold(gray, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cv2.imshow("Otsu", thresh)
options = "--psm 3 -c tessedit_char_whitelist=0123456789"
text = pytesseract.image_to_string(thresh, config=options)
print(text)
cv2.waitKey(0)
解决方案
1. Detect the ID in the image.
2. Crop the ID from the image.
3. Resize the cropped image to a fixed size.
4. Apply OCR to the resized image.
检查这个: https ://github.com/souravs17031999/ID-Extractor-from-Coil
import cv2
import numpy as np
import pytesseract
from PIL import Image
# Path of working folder on Disk
def get_string(img_path):
# Read image with opencv
img = cv2.imread(img_path)
# Convert to gray
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
# Write image after removed noise
cv2.imwrite("removed_noise.png", img)
# Apply threshold to get image with only black and white
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
# Write the image after apply opencv to do some ...
cv2.imwrite(img_path, img)
# Recognize text with tesseract for python
result = pytesseract.image_to_string(Image.open(img_path))
# Remove template file
return result
推荐阅读
- java - XML:faxterxml 无法通过忽略 xml 属性反序列化 xml 元素
- unit-testing - 您是否使用 Jest 和 React 测试库对您的 react-admin 应用程序进行自动化测试?
- ios - 确定何时以及如何在 iOS 中更改消息设置
- javascript - 如何将输入数据和复选框从表单发送到服务器?
- laravel - laravel 返回用户不是在数组中,而是在嵌套在对象中的对象中
- reactjs - 如何忽略嵌套堆栈的 React Navigation 状态持久性?
- itfoxtec-identity-saml2 - ITfoxtec 身份包的文档位置?
- java - 我需要从生成的号码中点击移动键盘
- javascript - 如何检测用户是否在 Instagram 上关注您?
- vue.js - 使用 Vue 在 Ionic 5 中自定义 webpack 配置