老板的項目需要用深度學習處理圖像,其中有一個小的環節是自動識別圖像拍攝的時間,這個最簡單直接的就是用OCR識別。google了一下,在GitHub上也找了找,最終確定了用 opencv + tesseract的方案。
先上 一下圖片
需要識別的數字區域
這是從原始的圖像中截取的一部分。因為所有的數字區域都在圖像相同的位置,可以用像素點位置固定截圖。奇怪的是,我最開始是剛好沿著白框截的,識別的效果很不好。后來想到同事用Halcon處理時,截的區域比較大,我也就擴大了些,結果效果變好了。
代碼如下
# 導入要用的包
import os
import numpy as np
import cv2
from PIL import Image
import matplotlib
%matplotlib inline
import pytesseract
from pytesseract import Output
# 圖像預處理
# get grayscale image
def get_grayscale(image):
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# noise removal
def remove_noise(image):
return cv2.medianBlur(image,5)
#thresholding
def thresholding(image):
return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
#dilation
def dilate(image):
kernel = np.ones((5,5),np.uint8)
return cv2.dilate(image, kernel, iterations = 1)
#erosion
def erode(image):
kernel = np.ones((5,5),np.uint8)
return cv2.erode(image, kernel, iterations = 1)
#opening - erosion followed by dilation
def opening(image):
kernel = np.ones((5,5),np.uint8)
return cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)
#canny edge detection
def canny(image):
return cv2.Canny(image, 100, 200)
#skew correction
def deskew(image):
coords = np.column_stack(np.where(image > 0))
angle = cv2.minAreaRect(coords)[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
return rotated
#template matching
def match_template(image, template):
return cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
# 圖像中數字識別的主程序
def img_to_digit(img_path,crop_path):
img = cv2.imread(img_path)
# 這里是截取的含有數字的部分
img_c = img[700:800,700:800]
# 因為我的圖像就是黑白的,不進行預處理效果也很好。其他情況可以適當處理
#gray = get_grayscale(img_c)
#thresh = thresholding(gray)
#opening = opening(gray)
#canny = canny(gray)
cv2.imwrite(crop_path,img_c)
d = pytesseract.image_to_data(img_c, output_type=Output.DICT)
return d['text']