21 lines
713 B
Python
21 lines
713 B
Python
from PIL import Image, ImageFilter, ImageOps
|
|
import ddddocr
|
|
import io
|
|
|
|
def preprocess_image(image_path, threshold=160):
|
|
img = Image.open(image_path).convert('L') # 灰度
|
|
img = img.point(lambda x: 0 if x < threshold else 255, '1') # 二值化
|
|
img = img.filter(ImageFilter.MedianFilter(size=3)) # 去噪
|
|
img = ImageOps.invert(img.convert('L')).convert('1') # 反色处理
|
|
buf = io.BytesIO()
|
|
img.save(buf, format='PNG')
|
|
return buf.getvalue()
|
|
|
|
def recognize_image(image_path):
|
|
ocr = ddddocr.DdddOcr()
|
|
clean_image = preprocess_image(image_path)
|
|
return ocr.classification(clean_image)
|
|
|
|
if __name__ == '__main__':
|
|
print('识别结果:', recognize_image('picture.png'))
|