我正在尝试从图像 image here 中提取日期。日期位于右下角,所以我也尝试先裁剪图像然后尝试提取日期,但似乎没有一个工作。
import cv2
import pytesseract
import matplotlib.pyplot as plt
img = cv2.imread("datepic.jpg")
date = pytesseract.image_to_string(img,config='--psm 10 -c tessedit_char_whitelist=0123456789')
date
##cropping the image to get only the date part
from PIL import Image
img = Image.open("datepic.jpg")
left =320
right = 460
top = 330
bottom = 350
m1 = img.crop((left, top, right, bottom))
plt.imshow(m1)
date = pytesseract.image_to_string(m1, config='-psm 9 tessedit_char_whitelist=0123456789')
date
我也玩过 psm 值,但没有一个给出预期的结果。
答案 0 :(得分:0)
使用日期位于右下角的信息,我们可以估计它的位置。接下来,我们可以对图像进行上采样和颜色分割以进行准确识别,使数字对于人眼和 tesseract 都更加可见。最后,我们应用自适应阈值来提取和 OCR 字母。
cv2.resize
)裁剪区域以使其可见。为了执行颜色分割,我们需要将裁剪区域转换为 HSV 格式,定义下/上范围并使用 cv2.inRange
执行颜色分割以获得二值掩码。cv2.bitwise_and
将日期部分与图像的其余部分分开。算术运算 and
对于在 hsv 彩色图像中定义 roi 非常有用。simple-thresholding methods
没有用。我们将使用 cv2.adaptiveThreshold
使特征可被超立方体检测到。请注意,blockSize
和 C
参数可能因图像而异。page-segmentation-mode
。我们只需使用 image_to_string
而不进行任何配置即可获得结果。步骤
估计日期位置:
由颜色分割生成的蒙版
使用 bitwise_and 提取日期部分
应用自适应阈值
tesseract-ocr 的结果
01/02/2021.14:213
代码:
import cv2
import numpy as np
import pytesseract
# Estimate the position
img = cv2.imread("QqLso.jpg")
(h, w) = img.shape[:2]
crp = img[h-30:h, int((3*w)/5):w]
# Up-sample
crp = cv2.resize(crp, (0, 0), fx=5, fy=5)
# Create binary mask
hsv = cv2.cvtColor(crp, cv2.COLOR_BGR2HSV)
lwr = np.array([0, 102, 0])
upr = np.array([179, 255, 255])
msk = cv2.inRange(hsv, lwr, upr)
# Remove background
res = 255 - cv2.bitwise_and(crp, crp, mask=msk)
# Adaptive-threshold
crp_img = cv2.cvtColor(res, cv2.COLOR_HSV2BGR)
crp_gry = cv2.cvtColor(crp_img, cv2.COLOR_BGR2GRAY)
thr = cv2.adaptiveThreshold(crp_gry, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY_INV, 31, 9)
# OCR
txt = pytesseract.image_to_string(thr)
print(txt)
# display
cv2.imshow("thr", thr)
cv2.waitKey(0)
要查找掩码的上下边界,您可能会发现有用:HSV-Threshold-script