效果
先来看下效果
检测结果:
思路
- 原图转灰度图
- 对灰度图进行高斯滤波、中值滤波去噪
- 使用sobel算子计算梯度(即提取边缘),这里考虑到车牌上字都是瘦长的,所以我这里只用了水平梯度,这样可以避免环境的干扰
- 对梯度图进行高斯滤波去除细节
- 转二值图
- 腐蚀1次,膨胀10次,来使车牌整体连接成一个白色色块
- 寻找围成面积最大的轮廓,进行方向校正,最后画出
代码
import cv2
import numpy as np
#读取图片
imagePath = 'car.jpg'
img = cv2.imread(imagePath)
#转灰度图
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#高斯滤波+中值滤波
img_gaus = cv2.GaussianBlur(img_gray,(3,3),0,0,cv2.BORDER_DEFAULT)
img_median = cv2.medianBlur(img_gaus,3)
#使用sobel算子计算梯度 只计算水平方向
#转成64位float是为了保留梯度中的负值
x = cv2.Sobel(img_median,cv2.CV_64F,1,0,ksize = 3)
gra = cv2.convertScaleAbs(x)
#再次高斯滤波 去除噪声
blurred = cv2.GaussianBlur(gra,(9,9),0)
#转二值图
_,thresholded = cv2.threshold(blurred,100,255,cv2.THRESH_BINARY)
#选用了十字架核
kernel1 = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
#腐蚀膨胀
erode = cv2.erode(thresholded,kernel1,iterations= 1)
dilate = cv2.dilate(erode,kernel1,iterations=10)
#找轮廓
cnt,_ = cv2.findContours(dilate.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
c = sorted(cnt, key=cv2.contourArea, reverse=True)[0]
rect = cv2.minAreaRect(c)
Box = np.int0(cv2.boxPoints(rect))
#轮廓校正
x1 = np.max(Box[...,0])
x2 = np.min(Box[...,0])
y1 = np.max(Box[...,1])
y2 = np.min(Box[...,1])
new_box= np.array([[x2,y2],[x2,y1],[x1,y1],[x1,y2]])
#展示效果
Final_img = cv2.drawContours(img.copy(), [new_box], -1, (0, 0, 255), 3)
cv2.imshow('License',Final_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('tmp.jpg',Final_img)