車牌偵測及辨識

      在〈車牌偵測及辨識〉中尚無留言

車牌偵測及辨識

車牌模型訓練後產生 best.pt 模型,此檔即可開始偵測車牌位置。偵測到車牌後,就可以將車牌切割出來,然後使用 tesseract OCR進行辨識。

無法訓練模型的人,請由此下載 : best.pt。下載完後,請將 best.pt 放置在 runs/train/yolov7/weights 之下。

車牌偵測

修改 detect.py 檔,新增如下藍色部份

def detect(save_img=False, myopt=None):
    global opt
    if myopt is not None: opt=myopt
    source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
    save_img = not opt.nosave and not source.endswith('.txt')  # save inference images
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://', 'https://'))
    .......
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        xys=[]
        for i, det in enumerate(pred):  # detections per image
    ......
                    if save_img or view_img:  # Add bbox to image
                        label = f'{names[int(cls)]} {conf:.2f}'
                        plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
                    xys.append(xyxy)
    .........
    print(f'Done. ({time.time() - t0:.3f}s)')
    return im0, xys

然後新增 “車牌偵測.py” 檔,代碼如下。請注意,因為訓練時指定訓練的圖片為 640 * 640 ,所以在偵測時, opt.img_size 亦要指定為 640,否則會偵測錯誤

import argparse
import numpy as np
import pylab as plt
import matplotlib
import cv2
import torch
from PIL import Image, ImageFont, ImageDraw
from detect import detect
import pytesseract
parser = argparse.ArgumentParser()
opt = parser.parse_args()
opt.weights='./runs/train/yolov7/weights/best.pt'
opt.img_size = 640
opt.source = "test/4.jpg"
opt.view_img=False
opt.save_txt=False
opt.save_conf=False
opt.classes=None#None才會標示框線
opt.no_trace=False
opt.nosave=False#要儲存,才會畫框線
opt.project='runs/detect'
opt.name='exp'
opt.exist_ok=True #True才不會一直新增目錄
opt.device='0'#使用GPU 0裝置
opt.augment=False
opt.conf_thres=0.25
opt.iou_thres=0.45
opt.agnostic_nms=False
opt.update=False

img=cv2.imdecode(np.fromfile(opt.source, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
with torch.no_grad():
    im0, xys=detect(myopt=opt)
matplotlib.use('qt5agg')
pil=Image.fromarray(im0[:,:,::-1])
plt.axis("off")
plt.imshow(pil)
plt.show()

請注意,matplotlib 無法進行繪圖,需將模式設定為 qt5agg 才能繪圖

切割車牌及辨識

底下完整代碼將把車牌切割出來,然後使用 tesseract ocr 辨識

🔒 底下內容僅限會員閱讀。

立即登入

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *