某天回家之時,聽到有個朋友說起他正在做一個車牌識別的項目
于是對其定位車牌的位置算法頗有興趣,今日有空得以研究,事實上車牌識別算是比較成熟的技術了,
這里我只是簡單實現。
我的思路為:
對圖片進行一些預處理,包括灰度化、高斯平滑、中值濾波、Sobel算子邊緣檢測等等。
利用OpenCV對預處理后的圖像進行輪廓查找,然后根據一些參數判斷該輪廓是否為車牌輪廓。
效果如下:
test1:
test2
實現代碼如下(對圖像預處理(濾波器等)的原理比較簡單,這里只是對一些函數進行調包):
import cv2 import numpy as np # 形態學處理 def Process(img): # 高斯平滑 gaussian = cv2.GaussianBlur(img, (3, 3), 0, 0, cv2.BORDER_DEFAULT) # 中值濾波 median = cv2.medianBlur(gaussian, 5) # Sobel算子 # 梯度方向: x sobel = cv2.Sobel(median, cv2.CV_8U, 1, 0, ksize=3) # 二值化 ret, binary = cv2.threshold(sobel, 170, 255, cv2.THRESH_BINARY) # 核函數 element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1)) element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 7)) # 膨脹 dilation = cv2.dilate(binary, element2, iterations=1) # 腐蝕 erosion = cv2.erode(dilation, element1, iterations=1) # 膨脹 dilation2 = cv2.dilate(erosion, element2, iterations=3) return dilation2 def GetRegion(img): regions = [] # 查找輪廓 _, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: area = cv2.contourArea(contour) if (area < 2000): continue eps = 1e-3 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, eps, True) rect = cv2.minAreaRect(contour) box = cv2.boxPoints(rect) box = np.int0(box) height = abs(box[0][1] - box[2][1]) width = abs(box[0][0] - box[2][0]) ratio =float(width) / float(height) if (ratio < 5 and ratio > 1.8): regions.append(box) return regions def detect(img): # 灰度化 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) prc = Process(gray) regions = GetRegion(prc) print('[INFO]:Detect %d license plates' % len(regions)) for box in regions: cv2.drawContours(img, [box], 0, (0, 255, 0), 2) cv2.imshow('Result', img) #保存結果文件名 cv2.imwrite('result2.jpg', img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == '__main__': #輸入的參數為圖片的路徑 img = cv2.imread('test2.jpg') detect(img)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
