opencv车牌识别python代码
时间: 2023-10-11 13:11:26 浏览: 73
利用Python opencv进行车牌识别
5星 · 资源好评率100%
以下是基于OpenCV实现的Python代码,用于识别车牌。
```
import cv2
import numpy as np
# 读取图片
img = cv2.imread('car.jpg')
# 将图片转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯滤波
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# 边缘检测
edges = cv2.Canny(blur, 50, 200)
# 膨胀操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
dilate = cv2.dilate(edges, kernel)
# 查找轮廓
contours, hierarchy = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 查找矩形轮廓
rects = []
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
if area > 500 and w > h:
rects.append((x, y, w, h))
# 对矩形轮廓进行排序
rects = sorted(rects, key=lambda x: x[0])
# 识别车牌号码
plate = ''
for rect in rects:
x, y, w, h = rect
roi = gray[y:y+h, x:x+w]
th = cv2.threshold(roi, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
text = pytesseract.image_to_string(th, config='--psm 7')
plate += text
# 显示识别结果
print('车牌号码:', plate)
cv2.imshow('img', img)
cv2.imshow('edges', edges)
cv2.imshow('dilate', dilate)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
需要注意的是,这段代码中使用了OCR(Optical Character Recognition,光学字符识别)技术来识别车牌号码,需要安装tesseract-ocr和pytesseract库。在安装完这两个库后,需要将pytesseract.image_to_string()函数的config参数设置为'--psm 7',这样才能正确识别车牌号码。
阅读全文