PIL+tesserocr
pip install pillow
pip install pytesseract
PIL
进行预处理。经历步骤:
灰度化->降噪(去除噪声)->二值化->分割->识别
灰度处理
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
img = Image.open('1.png')
img = np.array(img)
print(img)
if img.ndim == 3:
img = img[:,:,1] # 取三个通道中的第1个数据,编号从0开始
print(img)
plt.imshow(img, cmap = plt.cm.gray_r)
plt.show()
PIL
库自带方法实现灰度化
from PIL import Image
img = Image.open('1.png')
im_gray = img.convert('L')
im_gray.show()
稍微百度了下,发现灰度化的方法其实很多,如分量法、最大值法、平均值法、加权平均法,详情参考here
名称 | 解释 |
---|---|
分量法 | 该方法最为简单,即在R 、G 、B 三种颜色分量中,任意选取一种颜色作为灰度值 |
最大值法 | 该方法是先找出每个像素R 、G 、B 三种颜色分量的值,然后找到值最大的那个颜色,然后以此最大值作为灰度值 |
平均值法 | 该方法是先找到像素的R 、G 、B 三种颜色的分量值,最后置灰度值为三个分量值的平均值即可。 |
加权平均法 | 因为人眼对每种颜色的敏感度不同,其中人眼对绿色敏感度最高,蓝色敏感度最低,所以我们可以使用加权平均的方法来求灰度值,公式如下: f ( x , y ) = a i R ( i , j ) + b i G ( i , j ) + c i B ( i , j ) f(x,y)=a _iR(i,j)+b_iG(i,j)+c_iB(i,j) f(x,y)=aiR(i,j)+biG(i,j)+ciB(i,j) |
here也有相应的实现。
二值化
二值化的作用:
简单通俗的说:二值化的所用就是将图像分成黑和白(就不是上面的灰度图),更加有利于做图像处理判别
。
here深度好文。
验证码识别
import pytesseract
from PIL import Image
#获得图片
img = Image.open('1.png')
img.show()
# 图像灰度化处理
image = img.convert('L')
# 二值化
threshold = 125
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1')
image.show()
# 识别
str = pytesseract.image_to_string(image, lang='eng', config='--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789')
print(str)
安装参考:here