opencv车牌识别代码
时间: 2023-07-29 10:08:53 浏览: 158
以下是一个基于OpenCV的车牌识别代码示例,包含车牌定位、字符分割和字符识别三个部分:
```python
import cv2
import numpy as np
# 车牌定位
def locate_car_plate(img):
# 预处理:灰度化、高斯模糊、边缘检测
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 100, 200)
# 车牌定位:颜色过滤、形态学变换
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([100, 50, 50])
upper_blue = np.array([140, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (17, 5))
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
opened = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel)
contours, hierarchy = cv2.findContours(opened, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 找到最大的轮廓
maxContour = None
maxArea = 0
for contour in contours:
area = cv2.contourArea(contour)
if area > maxArea:
maxArea = area
maxContour = contour
# 找到包含车牌的最小矩形
rect = cv2.minAreaRect(maxContour)
box = np.int0(cv2.boxPoints(rect))
return box
# 字符分割
def segment_characters(img):
# 预处理:灰度化、二值化、去噪
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
# 字符分割:垂直投影
h, w = opened.shape[:2]
x_axis = np.sum(opened, axis=0)
x_axis = x_axis / h
x_axis = np.uint8(x_axis)
x_axis = cv2.resize(x_axis, (w, 1))
_, x_axis = cv2.threshold(x_axis, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(x_axis, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 分割出每个字符
boxes = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
if w > h and w > 10 and h > 20:
boxes.append([x, y, w, h])
# 对字符按照位置进行排序
boxes = sorted(boxes, key=lambda x: x[0])
return boxes
# 字符识别
def recognize_characters(img, boxes, model):
result = ""
for box in boxes:
x, y, w, h = box
char_img = img[y:y + h, x:x + w]
char_img = cv2.resize(char_img, (20, 20))
char_img = char_img.reshape((1, -1))
char_img = np.float32(char_img)
_, result_, _, _ = model.predict(char_img)
result += str(chr(int(result_[0][0])))
return result
# 主函数
if __name__ == "__main__":
# 加载模型
model = cv2.ml.KNearest_create()
model.load("knn_model.xml")
# 加载图片
img = cv2.imread("car_plate.jpg")
# 定位车牌
box = locate_car_plate(img)
cv2.drawContours(img, [box], -1, (0, 255, 0), 2)
# 分割字符
x, y, w, h = cv2.boundingRect(box)
plate_img = img[y:y + h, x:x + w]
boxes = segment_characters(plate_img)
# 识别字符
result = recognize_characters(plate_img, boxes, model)
# 显示结果
cv2.imshow("Image", img)
print("车牌号码:", result)
cv2.waitKey(0)
```
需要注意的是,这里使用了KNN模型进行字符识别,需要在运行代码之前训练好模型并保存为XML文件。具体训练过程可以参考OpenCV官方文档。
阅读全文