利用python进行车牌识别
-
图像读取 -
图像增强 -
车牌位置识别 -
排除无用信息 -
文字提取 文本提取没有进行cnn学习,识别度不高,要求车牌方向不太歪,字迹清晰
相关说明:
- 利用pip install 导入相关库:例如win+r—cmd—pip install numpy
- 利用python的pytesseract库以及tesseract下载链接识别文本(tesseract需要配置环境变量)
完整代码如下
import cv2
import imutils
import numpy as np
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
#获取图像
imgFile = 'D:
img = cv2.imread(imgFile, cv2.IMREAD_COLOR)
img = cv2.resize(img, (620, 480))
#卷积模板
kernel_sharpen_2 = np.array([
[1,1,1],
[1,-7,1],
[1,1,1]])
#卷积
output_2 = cv2.filter2D(img,-1,kernel_sharpen_2)
#显示锐化效果
cv2.imshow('sharpen_2 Image',output_2)
#停顿
if cv2.waitKey(0) & 0xFF == 27:
cv2.destroyAllWindows()
#灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#滤波
gray = cv2.bilateralFilter(gray, 13, 15, 15)
#边缘检测
edged = cv2.Canny(gray, 30, 200)
cv2.imshow('car',edged)
if cv2.waitKey(0) & 0xFF == 27:
cv2.destroyAllWindows()
#找轮廓
contours = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:50]
screenCnt = None
#print(contours)
#cv2.drawContours(img, contours,-1, (0, 0, 255), 3)
#识别车牌
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.015 * peri, True)
#print(approx)
#print(len(approx))
if len(approx) == 4:
screenCnt = approx
break
#画框
if screenCnt is None:
detected = 0
print("No contour detected")
else:
detected = 1
if detected == 1:
cv2.drawContours(img, [screenCnt], -1, (0, 0, 255), 3)
#print(screenCnt)
#cv2.imshow('car',img)
#cv2.waitKey(0)
#去除无用信息
mask = np.zeros(gray.shape, np.uint8)
new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1, )
new_image = cv2.bitwise_and(img, img, mask=mask)
#cv2.imshow('car',new_image)
#cv2.waitKey(0)
#分割出来
(x, y) = np.where(mask == 255)
(topx, topy) = (np.min(x), np.min(y))
(bottomx, bottomy) = (np.max(x), np.max(y))
Cropped = gray[topx:bottomx + 1, topy:bottomy + 1]
cv2.imshow('car',Cropped)
if cv2.waitKey(0) & 0xFF == 27:
cv2.destroyAllWindows()
text = pytesseract.image_to_string(Cropped ,config='--psm 11')
print("programming_fever's License Plate Recognition\n")
print("Detected license plate Number is:", text)
img = cv2.resize(img, (500, 300))
Cropped = cv2.resize(Cropped, (400, 200))
cv2.imshow('car', img)
cv2.imshow('Cropped', Cropped)
if cv2.waitKey(0) & 0xFF == 27:
cv2.destroyAllWindows()
有时间会对代码进行优化以及添加相关函数的用法
|