40 lines of manual license plate detection (python+opencv)! Very simple

effect

First look at the effect

Test results:

 

 

 

Ideas

  1. Original image to grayscale

  2. Perform Gaussian filtering, median filtering and denoising on grayscale images

  3. Use the sobel operator to calculate the gradient (that is, extract the edge). Considering that the words on the license plate are all thin and long, I only use the horizontal gradient here to avoid environmental interference

  4. Gaussian filtering of the gradient map to remove details

  5. Convert Binary Graph

  6. Corrosion once and expand 10 times to connect the license plate into a white color block

  7. Find the contour with the largest enclosed area, correct the direction, and finally draw

 

 

Code

import cv2 
import numpy as np #read the 

picture 
imagePath ='car.jpg' 
img = cv2.imread(imagePath) #turn 

to grayscale 
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #Gaussian 

filter + median filter 
img_gaus = cv2.GaussianBlur(img_gray,(3,3),0,0,cv2.BORDER_DEFAULT) 
img_median = cv2.medianBlur(img_gaus,3) #Use the 

sobel operator to calculate the gradient and only calculate the horizontal direction 
#The purpose of turning into a 64-bit float Keep the negative values ​​in the gradient 
x = cv2.Sobel(img_median,cv2.CV_64F,1,0,ksize = 3) 
gra = cv2.convertScaleAbs(x) #Gaussian 

filtering again to remove noise 
blurred = cv2.GaussianBlur(gra,(9 , 9), 0) 

# turn binary picture 
_, = cv2.threshold thresholded (, blurred, 100,255, cv2.THRESH_BINARY) 

# cross selected nuclear 
kernel1 = cv2.getStructuringElement (cv2.MORPH_CROSS, (3,3)) 

# corrosion Swell
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)

Recently, many friends consulted about Python learning issues through private messages. To facilitate communication, click on the blue to join the discussion and answer resource base by yourself

 

Guess you like

Origin blog.csdn.net/weixin_43881394/article/details/112468256