环境:Python3, Windows
首先先得安装Pillow和pytesseract:
pip install pytesseract
pip install pillow
之后需要在操作系统里安装Tesseract:
- 访问https://github.com/UB-Mannheim/tesseract/wiki
- 下载tesseract-ocr-w64-setup-v4.1.0.20190314 (rc1)
- 安装下载好的tesseract-ocr-w64-setup-v4.1.0.20190314.exe,安装过程中最好选择Chinese(simplified)语言
- 安装完毕后,将tesseract的目录(默认“C:\Program Files\Tesseract-OCR”)加入到系统PATH变量中
使用Windows CMD确认安装结果:
C:\Users\xxx>tesseract -v
tesseract v4.0.0.20190314
leptonica-1.78.0
libgif 5.1.4 : libjpeg 8d (libjpeg-turbo 1.5.3) : libpng 1.6.34 : libtiff 4.0.9 : zlib 1.2.11 : libwebp 0.6.1 : libopenjp2 2.2.0
Found AVX2
Found AVX
Found SSE
C:\Users\xxx>tesseract --list-langs
List of available languages (4):
chi_sim
eng
osd
script/HanS
tesseract-4.0.0a支持以下psm参数:
Page segmentation modes:
0 Orientation and script detection (OSD) only.
1 Automatic page segmentation with OSD.
2 Automatic page segmentation, but no OSD, or OCR.
3 Fully automatic page segmentation, but no OSD. (Default)
4 Assume a single column of text of variable sizes.
5 Assume a single uniform block of vertically aligned text.
6 Assume a single uniform block of text.
7 Treat the image as a single text line.
8 Treat the image as a single word.
9 Treat the image as a single word in a circle.
10 Treat the image as a single character.
11 Sparse text. Find as much text as possible in no particular order.
12 Sparse text with OSD.
13 Raw line. Treat the image as a single text line,
bypassing hacks that are Tesseract-specific.
python3 用法:
from PIL import Image
import pytesseract
img = Image.open('shot.png')
ocr_str = pytesseract.image_to_string(img, lang="eng", config="--psm 7")
print(ocr_str)
如果图片中是纯数字,可以使用:
ocr_str = pytesseract.image_to_string(image, lang='eng', \
config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789')