Python 实现简单车牌识别
Ubuntu系统:22.04
python版本:3.9
安装依赖库:
pip install opencv-python numpy easyocr -i https://mirrors.aliyun.com/pypi/simple
代码实现:
import cv2
import numpy as np
import easyocr# 初始化EasyOCR阅读器(自动下载预训练模型)
reader = easyocr.Reader(['ch_sim', 'en']) # 使用简体中文和英文模型def license_plate_recognition(img_path):# 读取图像img = cv2.imread(img_path)if img is None:print("Error: 无法读取图像文件")return# 颜色过滤(针对蓝牌车)hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)lower_blue = np.array([100, 80, 80])upper_blue = np.array([140, 255, 255])mask = cv2.inRange(hsv, lower_blue, upper_blue)# 形态学操作kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20))closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)# 查找轮廓contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 筛选可能车牌区域plate = Nonefor cnt in contours:x, y, w, h = cv2.boundingRect(cnt)aspect_ratio = w / hif 2 < aspect_ratio < 5 and w > 100: # 根据宽高比和尺寸筛选plate = img[y:y+h, x:x+w]breakif plate is None:print("未检测到车牌")return# 使用EasyOCR识别文字results = reader.readtext(plate, detail=0)# 合并识别结果if results:return "".join(results)return "识别失败"# 使用示例
if __name__ == "__main__":plate_number = license_plate_recognition("car.jpg") # 替换为你的图片路径print("识别结果:", plate_number)
注意事项:
1、首次运行需要网络连接,自动下载预训练模型,网络不稳定会存在失败,多试几次就可以了
2、准确率一般般,实测会存在误测的问题,这个仅供参考