将图像翻译成文字称为光学文字识别(Optical Character Recognition,OCR)
OCR库
Pillow,Tesseract,NumPy.
利用Pillow库,创建一个过滤器来去掉渐变的背景色,只把文字留下来。
example1
from PIL import Image
import subprocess
def cleanFile(filePath,newFilePath):
image = Image.open(filePath)
#对图片进行过滤,然后保存
image = image.point(lamba x:0 if x<143 else 255)
image.save(newFilePath)
#调用系统的tesseract命令对图片进行OCR识别
subprecess.call(['tesseract',newFilePath,'output'])
#打开文件读取结果
outputFile = open('output.txt','r')
print(outputFile.read())
outputFile.close()
cleanFile('text_2,jpg','text_2_clean.png')
example2
利用pyocr最基本的黑白图片
from PIL import Image
from pyocr import tesseract
# 使用PIL打开图片
im = Image.open('pic_file')
# ORC识别
code = tesseract.image_to_string(im)
print(code)
example3
from PIL import Image
from pyocr import tesseract
pic_list = ['pic1.png', 'pic2.png']
for i in pic_list:
im = Image.open(i)
im = im.convert('L') # 图片转化成灰色图像
im.save("temp.png")
code = tesseract.image_to_string(im)
print(code)
除了使用ORC识别,还可以利用第三方平台实现验证码的识别。
学习中遇到比较好的关于图片识别的库
face_recognition
ImageAI
云打码平台