Python使用OpenCV识别车牌号

Python怎么使用OpenCV识别车牌号?

步骤如下:

  1. 预处理图片,包括灰度化、高斯滤波、二值化等操作,提取出车牌区域;

  2. 使用形态学运算(如闭运算)和轮廓检测来进一步过滤噪声和提取车牌号码;

  3. 使用OCR识别车牌号码。

Python示例代码

以下是基于OpenCV和Tesseract OCR库的Python示例代码:

import cv2
import numpy as np
import pytesseract

# 预处理
def preprocessing(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5,5), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    return thresh

# 车牌区域检测
def plate_detection(img):
    thresh = preprocessing(img)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))
    closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    cnts, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 车牌区域筛选
    plate_area = None
    for c in cnts:
        x,y,w,h = cv2.boundingRect(c)
        ar = w / float(h)
        if ar > 2.5 and ar < 5 and w > 100 and h > 30:
            plate_area = (x, y, w, h)
            break

    return plate_area

# OCR识别
def ocr(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray, 3)
    text = pytesseract.image_to_string(gray, lang='eng', config='--psm 7')
    return text

# 主函数
if __name__ == '__main__':
    img = cv2.imread('car.jpg')
    plate_area = plate_detection(img)
    if plate_area is not None:
        x, y, w, h = plate_area
        plate_img = img[y:y+h, x:x+w]
        plate_text = ocr(plate_img)
        print('车牌号码:', plate_text)
    else:
        print('未检测到车牌区域')

在这个示例中,我们首先调用preprocessing函数对图像进行预处理,然后使用形态学运算和轮廓检测来检测车牌区域并提取出车牌图像;最后调用ocr函数对车牌图像进行OCR识别,得到车牌号码。

Leave a Comment

豫ICP备19001387号-1