pythonimport pytesseractfrom PIL import Imagedef recognize_chinese_textimg_path # 读取图片 img = Imageopenimg_path # 转化为灰度图像 img = imgconvertL # 二值化处理 threshold = 140 table = for
,加入异常处理和注释:
import pytesseract
from PIL import Image
def recognize_chinese_text(img_path):
try:
# 读取图片
img = Image.open(img_path)
# 转化为灰度图像
img = img.convert('L')
# 二值化处理
threshold = 140
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
img = img.point(table, '1')
# 识别中文文字
text = pytesseract.image_to_string(img, lang='chi_sim')
return text
except Exception as e:
print(e)
return None
该函数输入参数为图片路径,返回值为识别出来的中文文字。如果发生异常,会输出异常信息并返回 None。
原文地址: https://www.cveoy.top/t/topic/boL7 著作权归作者所有。请勿转载和采集!