首页 > 技术知识 > 正文

本文是通过opencv识别图片所含车牌的简单案例。

环境安装

首先你要有python环境,本文基于python3.6.3

安装命令:pip install opencv-python

然后测试下安装情况 import cv2 如果没有报错就可以了

如果报错缺少dll文件或者python版本与opencv版本不匹配导致找不到模块,可参考下发链接中的安装方法。 https://blog.csdn.net/weixin_43582101/article/details/88660570

如果没有matplotlib,也需要安装一下 pip install matplotlib

导入模块 import cv2 import numpy as np import matplotlib.pyplot as plt 读取图片

使用cv2.imdecode()函数定义一个读取图片的方法 (从内存缓存中读取数据,并把数据解码成图像格式)

def imreadex(filename): return cv2.imdecode(np.fromfile(filename, dtype=np.uint8), cv2.IMREAD_COLOR)

python-opencv车牌识别

图像降噪

首先进行颜色翻转,既改变RGB,转为黑白两色 img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

python-opencv车牌识别1 (图像处理中,常用的滤波算法有均值滤波、中值滤波以及高斯滤波等) 然后采用 GaussianBlur高斯滤波,对图像邻域内像素进行平滑时,邻域内不同位置的像素被赋予不同的权值。 cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) 进行形态学变化 接着把图像模糊、提取轮廓。在python中的使用: img = cv2.GaussianBlur(img, (blur, blur), 0)

python-opencv车牌识别2

阈值分割

图像阈值化分割是一种传统的最常用的图像分割方法,用cv2.threshold给图片设置阈值 cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 查找水平直方图波峰,确定主区域

x_h = np.sum(gmg, axis=1) rm, cm = gmg.shape[:2]

python-opencv车牌识别3

边缘检测

cv2.Canny(img_thresh, 100, 200) # Canny算法进行边缘检测

Canny(image, threshold1, threshold2[, edges[, apertureSize[, L2gradient]]]) -> edges brief Finds edges in an image using the Canny algorithm @cite Canny86 . The function finds edges in the input image and marks them in the output map edges using the Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The largest value is used to find initial segments of strong edges.

Canny边缘检测步骤: 1:高斯滤波除噪 2:sobel算子计算梯度 3:消除杂散效应 4:双阈值确定边缘 5:边缘检测

python-opencv车牌识别4

车牌定位

通过转变颜色空间来增加对比度 cv2.cvtColor(card_img, cv2.COLOR_BGR2GRAY) 查找水平直方图波峰,用来确定当前图片中车牌的主区域 水平方向的阈值为最小值和均值的均值。

查找图像边缘整体形成的矩形区域,可能有很多,车牌就在其中一个矩形区域中

image, contours, hierarchy = cv2.findContours(img_edge2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = [cnt for cnt in contours if cv2.contourArea(cnt) > Min_Area]

最後利用宽高比排除不是车牌的矩形区域。

识别结果

需要代码和模型,可前往该链接进行下载: https://download.csdn.net/download/weixin_43582101/11252391 或者留下邮箱,稍后我发给你

猜你喜欢