一.简单的识别
from PIL import Image
import pytesseract
image = Image.open(path) 使用PIL库打开图片
image = image.resize((110, 50)) 使用resize缩放图片尺寸
code = pytesseract.image_to_string(image) 使用pytesseract识别
二.处理图片
1.二值化 转灰处理 方法一
def binary(img, threshold): 传 threshold 代表处理二值化阀值
img=Image.open(filename) img需要用Image 打开
img=img.convert('L') L 代表转灰处理
pixdata = img.load()
w, h = img.size
for y in range(h):
for x in range(w):
if pixdata[x, y] < threshold:
pixdata[x, y] = 0
else:
pixdata[x, y] = 255
return img
2.二值化 转灰处理 方法二
image = Image.open("code.jpg")
image = image.convert('L')
threshold = 100
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1')
code = tesserocr.image_to_text(image)
三.降噪
def depoint(img):
"""传入二值化后的图片进行降噪"""
pixdata = img.load()
w, h = img.size
for y in range(1, h - 1):
for x in range(1, w - 1):
count = 0
if pixdata[x, y - 1] > 245: # 上
count = count + 1
if pixdata[x, y + 1] > 245: # 下
count = count + 1
if pixdata[x - 1, y] > 245: # 左
count = count + 1
if pixdata[x + 1, y] > 245: # 右
count = count + 1
if pixdata[x - 1, y - 1] > 245: # 左上
count = count + 1
if pixdata[x - 1, y + 1] > 245: # 左下
count = count + 1
if pixdata[x + 1, y - 1] > 245: # 右上
count = count + 1
if pixdata[x + 1, y + 1] > 245: # 右下
count = count + 1
if count > 4:
pixdata[x, y] = 255
return img
以上传入 img 都需要用 Image 函数打开 才能处理