看了下这篇的TODO是二月就做了,但是一直拖到现在10月。也就是一个关键的前置摄像头那块没打通,所以这边也block了。
本来是可以用esp32 cam来做,后面想了想还是在linux上弄吧。终于,最近几天把树莓派的摄像头打通了。可以来玩一玩了。树莓派外挂Camera1(基操)-CSDN博客
这次直接就用的picamera2,代码如下:
import cv2
import pytesseract
from picamera2 import Picamera2
import numpy as np
# 初始化 Picamera2
picam2 = Picamera2()
camera_config = picam2.create_video_configuration(main={"size": (640, 480)})
picam2.configure(camera_config)
picam2.start()
# OpenCV 函数用于检测车牌
def detect_plate(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 转换为灰度图
blur = cv2.GaussianBlur(gray, (5, 5), 0) # 高斯模糊
edged = cv2.Canny(blur, 30, 200) # 边缘检测
contours, _ = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 轮廓检测
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10] # 选取前10个大轮廓
plate = None
for contour in contours:
approx = cv2.approxPolyDP(contour, 10, True) # 多边形逼近
if len(approx) == 4: # 车牌通常是矩形
x, y, w, h = cv2.boundingRect(approx)
plate = frame[y:y+h, x:x+w] # 裁剪车牌区域
break
return plate
# 主循环:捕获帧并进行车牌识别
try:
while True:
frame = picam2.capture_array() # 获取当前帧
plate_img = detect_plate(frame) # 检测车牌
if plate_img is not None:
# 预处理车牌图像以提高 OCR 识别准确性
plate_gray = cv2.cvtColor(plate_img, cv2.COLOR_BGR2GRAY)
_, plate_thresh = cv2.threshold(plate_gray, 150, 255, cv2.THRESH_BINARY)
# 使用 Tesseract 进行 OCR 识别车牌字符
plate_text = pytesseract.image_to_string(plate_thresh, config='--psm 8')
print("Detected License Plate Number:", plate_text)
# 在原始帧上显示检测到的车牌框和识别的车牌号码
#cv2.putText(frame, plate_text, (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
#cv2.imshow("License Plate", plate_img)
#cv2.imshow("Frame", frame)
'''if cv2.waitKey(1) & 0xFF == ord('q'):
break'''
finally:
picam2.stop()
cv2.destroyAllWindows()
里面还用了个pytesseract的库,看介绍说这个是用来做OCR的,好吧,我也是第一次用这个。
网上找了一个炫酷车牌
可以看到识别率还马马虎虎:
A88888能认出来,但是汉字现在还不行。
我想原因是第一这个代码不支持汉字,后面还是要用深度学习来做这题才行。。。