Python識別圖片
Python使用opencv、Pillow識別圖片。
需要用到系統級需要安裝tesseract-ocr,
python庫需要opencv-python
, Pillow
, pytesseract
步驟一般為下載圖片-->讀取圖片-->將圖片灰度化-->二值化-->去除圖片中的干擾線-->識別。
從網絡中直接獲取圖片並讀取
示例
import requests
import cv2
from io import BytesIO
import pytesseract
import numpy
from PIL import Image
image = Image.open(BytesIO(response.content))
cv_image = cv2.cvtColor(numpy.asarray(image), cv2.COLOR_RGB2BGR)
cv2.imwrite('./test.png', cv_image)
print pytesseract.image_to_string(cv_image)
使用`requests`庫,發送請求
`content`讀取出來的是Byte類型的數據
`response = requests.get(url).content`
使用Pillow的PIL從response中讀取圖片
`image = Image.open(BytesIO(response))`
將PIL讀取的圖片轉為opencv支持的Image格式,COLOR_RGB2BGR轉為灰度
`cv_image = cv2.cvtColor(numpy.asarray(image), cv2.COLOR_RGB2BGR)`
opencv從本地讀取圖片
image = cv2.imread(path)
opencv保存圖片到本地
cv2.imwrite(F:/images',image)