💻 源代码
import cv2
import numpy as np
def Process(img):
"""形态学处理"""
gaussian = cv2.GaussianBlur(img, (3, 3), 0)
median = cv2.medianBlur(gaussian, 5)
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
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 1.8 < ratio < 5:
regions.append(box)
return regions
def detect(img_path):
"""检测车牌"""
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
prc = Process(gray)
regions = GetRegion(prc)
for box in regions:
cv2.drawContours(img, [box], 0, (0, 255, 0), 2)
cv2.imwrite('result.jpg', img)
print(f'检测到 {len(regions)} 个车牌')
# 使用示例
detect('./test.jpg')