1. 程式人生 > 程式設計 >python+OpenCV實現車牌號碼識別

python+OpenCV實現車牌號碼識別

基於python+OpenCV的車牌號碼識別,供大家參考,具體內容如下

車牌識別行業已具備一定的市場規模,在電子警察、公路卡口、停車場、商業管理、汽修服務等領域已取得了部分應用。一個典型的車輛牌照識別系統一般包括以下4個部分:車輛影象獲取、車牌定位、車牌字元分割和車牌字元識別

1、車牌定位的主要工作是從獲取的車輛影象中找到汽車牌照所在位置,並把車牌從該區域中準確地分割出來
這裡所採用的是利用車牌的顏色(黃色、藍色、綠色) 來進行定位

#定位車牌
def color_position(img,output_path):
 colors = [([26,43,46],[34,255,255]),# 黃色
    ([100,[124,# 藍色
    ([35,[77,255]) # 綠色
    ]
 hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
 for (lower,upper) in colors:
  lower = np.array(lower,dtype="uint8") # 顏色下限
  upper = np.array(upper,dtype="uint8") # 顏色上限

  # 根據閾值找到對應的顏色
  mask = cv2.inRange(hsv,lowerb=lower,upperb=upper)
  output = cv2.bitwise_and(img,img,mask=mask)
  k = mark_zone_color(output,output_path)
  if k==1:
   return 1
  # 展示圖片
  #cv2.imshow("image",img)
  #cv2.imshow("image-color",output)
  #cv2.waitKey(0)
 return 0

2、將車牌提取出來

def mark_zone_color(src_img,output_img):
 #根據顏色在原始影象上標記
 #轉灰度
 gray = cv2.cvtColor(src_img,cv2.COLOR_BGR2GRAY)

 #影象二值化
 ret,binary = cv2.threshold(gray,cv2.THRESH_BINARY)
 #輪廓檢測
 x,contours,hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
 #drawing = img
 #cv2.drawContours(drawing,-1,(0,255),3) # 填充輪廓顏色
 #cv2.imshow('drawing',drawing)
 #cv2.waitKey(0)
 #print(contours)
 
 temp_contours = [] # 儲存合理的輪廓
 car_plates=[]
 if len(contours)>0:
  for contour in contours:
   if cv2.contourArea(contour) > Min_Area:
    temp_contours.append(contour)
   car_plates = []
   for temp_contour in temp_contours:
    rect_tupple = cv2.minAreaRect(temp_contour)
    rect_width,rect_height = rect_tupple[1]
    if rect_width < rect_height:
     rect_width,rect_height = rect_height,rect_width
    aspect_ratio = rect_width / rect_height
    # 車牌正常情況下寬高比在2 - 5.5之間
    if aspect_ratio > 2 and aspect_ratio < 5.5:
     car_plates.append(temp_contour)
     rect_vertices = cv2.boxPoints(rect_tupple)
     rect_vertices = np.int0(rect_vertices)
   if len(car_plates)==1:
    oldimg = cv2.drawContours(img,[rect_vertices],2)
    #cv2.imshow("che pai ding wei",oldimg)
    # print(rect_tupple)
    break

 #把車牌號截取出來
 if len(car_plates)==1:
  for car_plate in car_plates:
   row_min,col_min = np.min(car_plate[:,:],axis=0)
   row_max,col_max = np.max(car_plate[:,axis=0)
   cv2.rectangle(img,(row_min,col_min),(row_max,col_max),0),2)
   card_img = img[col_min:col_max,row_min:row_max,:]
   cv2.imshow("img",img)
  cv2.imwrite(output_img + '/' + 'card_img' + '.jpg',card_img)
  cv2.imshow("card_img.",card_img)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  return 1
 return 0

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。