代码
import cv2 as cv
import pytesseract
from PIL import Image
def recognize_text(image):
# 边缘保留滤波 去噪
blur =cv.pyrMeanShiftFiltering(image, sp=8, sr=60)
cv.imshow('dst', blur)
# 灰度图像
gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY)
# 二值化
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
print(f'二值化自适应阈值:{ret}')
cv.imshow('binary', binary)
# 形态学操作 获取结构元素 开操作
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 2))
bin1 = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
cv.imshow('bin1', bin1)
kernel = cv.getStructuringElement(cv.MORPH_OPEN, (2, 3))
bin2 = cv.morphologyEx(bin1, cv.MORPH_OPEN, kernel)
cv.imshow('bin2', bin2)
# 逻辑运算 让背景为白色 字体为黑 便于识别
cv.bitwise_not(bin2, bin2)
cv.imshow('binary-image', bin2)
# 识别
test_message = Image.fromarray(bin2)
text = pytesseract.image_to_string(test_message)
print(f'识别结果:{text}')
src = cv.imread(r'd:/python/psc.jpg')
cv.imshow('input image', src)
recognize_text(src)
cv.waitKey(0)
cv.destroyAllWindows()
报错
二值化自适应阈值:95.0
Traceback (most recent call last):
File "d:\python\import cv2 as cv yanzhengm2.py", line 34, in <module>
recognize_text(src)
File "d:\python\import cv2 as cv yanzhengm2.py", line 28, in recognize_text
text = pytesseract.image_to_string(test_message)
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\pytesseract\pytesseract.py", line 423, in image_to_string
return {
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\pytesseract\pytesseract.py", line 426, in <lambda>
Output.STRING: lambda: run_and_get_output(*args),
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\pytesseract\pytesseract.py", line 288, in run_and_get_output
run_tesseract(**kwargs)
File "C:\Users\123\AppData\Local\Programs\Python\Python39\lib\site-packages\pytesseract\pytesseract.py", line 264, in run_tesseract
raise TesseractError(proc.returncode, get_errors(error_string))
pytesseract.pytesseract.TesseractError: (1, "Tesseract Open Source OCR Engine v3.05.00dev with Leptonica read_params_file: Can't open
txt Warning in pixReadMemPng: work-around: writing to a temp file libpng warning: Application built with libpng-1.4.3 but running with 1.5.14 Error in pixReadStreamPng: png_ptr not made Error in pixReadMemPng: pix not read Error in pixReadMem: png: no pix returned Error during processing.")