🚗 车牌识别 (人工智能)

📋 功能说明
  • 使用OpenCV进行图像处理
  • 形态学处理提取车牌区域
  • 支持多种车牌检测
💻 源代码
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')
📦 运行环境
pip install opencv-python numpy
算法流程
  1. 高斯平滑去噪
  2. 中值滤波
  3. Sobel边缘检测
  4. 二值化
  5. 形态学处理
  6. 轮廓检测