ocr圖片識別通常可以利用tesserocr模塊,將圖片中內容識別出來並轉換為text並輸出
Tesserocr是python的一個OCR識別庫,是對tesseract做的一層python APT封裝。在安裝Tesserocr前,需要先安裝tesseract
tessrtact文件:
https://digi.bib.uni-mannheim.de/tesseract/
python安裝tessocr: 下載對應的.whl文件安裝(這個包pip方式容易出錯)
tesseract 與對應的tesserocr:
https://github.com/simonflueckiger/tesserocr-windows_build/releases
實現代碼如下:
from PIL import Image
import tesserocr
#tesserocr識別圖片的2種方法
img = Image.open("code.jpg")
verify_code1 = tesserocr.image_to_text(img)
#print(verify_code1)
verify_code2 = tesserocr.file_to_text("code.jpg")
#print(verify_code2)
但是,當圖片中干擾部分較多,如驗證碼內多余的線條干擾圖片的識別,識別后的內容不是很准確,就需要做一下處理,如轉灰度,二值化操作。
可以利用Image對象的convert()方法,傳入“L”,將圖片轉為灰度圖像;傳入1則對圖像進行二值處理(默認閾值127)
原驗證碼:

img = Image.open("code.jpg")
img_L = img.convert("L")
img_L.show()

也可以自己設置閾值
threshold = 100 #設置二值的閾值100
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
#point()返回給定查找表對應的圖像像素值的拷貝,變量table為圖像的每個通道設置256個值,為輸出圖像指定一個新的模式,模式為“L”和“P”的圖像進一步轉換為模式為“1”的圖像
image = img_L.point(table, "1")
image.show()

img_1 = tesserocr.image_to_text(image)
print(img_1)
>>5SA6
