【项目三、车牌检测+识别项目】四、使用LPRNet进行车牌识别 您所在的位置:网站首页 车牌识别没反应怎么回事 【项目三、车牌检测+识别项目】四、使用LPRNet进行车牌识别

【项目三、车牌检测+识别项目】四、使用LPRNet进行车牌识别

2024-07-06 04:40| 来源: 网络整理| 查看: 265

目录 前言一、数据集二、训练三、验证四、测试结果五、推理代码Reference

前言

马上要找工作了,想总结下自己做过的几个小项目。

之前已经总结过了我做的第一个项目:xxx病虫害检测项目,github源码地址:HuKai97/FFSSD-ResNet。CSDN讲解地址:

【项目一、xxx病虫害检测项目】1、SSD原理和源码分析【项目一、xxx病虫害检测项目】2、网络结构尝试改进:Resnet50、SE、CBAM、Feature Fusion【项目一、xxx病虫害检测项目】3、损失函数尝试:Focal loss

第二个项目:蜂巢检测项目,github源码地址:https://github.com/HuKai97/YOLOv5-ShuffleNetv2。CSDN讲解地址:

【项目二、蜂巢检测项目】一、串讲各类经典的卷积网络:InceptionV1-V4、ResNetV1-V2、MobileNetV1-V3、ShuffleNetV1-V2、ResNeXt、Xception。 【项目二、蜂巢检测项目】二、模型改进:YOLOv5s-ShuffleNetV2。

如果对YOLOv5不熟悉的同学可以先看看我写的YOLOv5源码讲解CSDN:【YOLOV5-5.x 源码讲解】整体项目文件导航,注释版YOLOv5源码我也开源在了Github上:HuKai97/yolov5-5.x-annotations,欢迎大家star!

之前一直在学习OCR相关的东西,就想着能不能做一个车牌识别的项目出来,刚好车牌检测也好做,直接用v5就可以了。我的打算是做一个轻量级的车牌识别项目,检测网络用的是YOLOv5s,识别网络有的是LPRNet。

这一节主要介绍下怎么训练LPRNet车牌识别模型。

车牌识别项目所有讲解:

【项目三、车牌检测+识别项目】一、CCPD车牌数据集转为YOLOv5格式和LPRNet格式【项目三、车牌检测+识别项目】二、使用YOLOV5进行车牌检测【项目三、车牌检测+识别项目】三、LPRNet车牌识别网络原理和核心源码解读【项目三、车牌检测+识别项目】四、使用LPRNet进行车牌识别

代码已全部上传GitHub:https://github.com/HuKai97/YOLOv5-LPRNet-Licence-Recognition

一、数据集

在项目文件 YOLOv5-LRPNet-Licence-Recognition 的同级目录建一个datasets文件,数据集这里写的很清楚:【项目三、车牌检测+识别项目】一、CCPD车牌数据集转为YOLOv5格式和LPRNet格式,制作好放在在datasets里面,我一般不会把数据和代码放在一起,那样pycharm打开非常慢。

二、训练

在tools下的train_lprnet.py,主要配置:

def get_parser(): parser = argparse.ArgumentParser(description='parameters to train net') parser.add_argument('--max_epoch', default=100, help='epoch to train the network') parser.add_argument('--img_size', default=[94, 24], help='the image size') parser.add_argument('--train_img_dirs', default=r"", help='the train images path') parser.add_argument('--test_img_dirs', default=r"", help='the test images path') parser.add_argument('--dropout_rate', default=0.5, help='dropout rate.') parser.add_argument('--learning_rate', default=0.01, help='base value of learning rate.') parser.add_argument('--lpr_max_len', default=8, help='license plate number max length.') parser.add_argument('--train_batch_size', default=128, help='training batch size.') parser.add_argument('--test_batch_size', default=128, help='testing batch size.') parser.add_argument('--phase_train', default=True, type=bool, help='train or test phase flag.') parser.add_argument('--num_workers', default=8, type=int, help='Number of workers used in dataloading') parser.add_argument('--cuda', default=True, type=bool, help='Use cuda to train model') parser.add_argument('--resume_epoch', default=0, type=int, help='resume iter for retraining') parser.add_argument('--save_interval', default=500, type=int, help='interval for save model state dict') parser.add_argument('--test_interval', default=500, type=int, help='interval for evaluate') parser.add_argument('--momentum', default=0.9, type=float, help='momentum') parser.add_argument('--weight_decay', default=2e-5, type=float, help='Weight decay for SGD') parser.add_argument('--lr_schedule', default=[20, 40, 60, 80, 100], help='schedule for learning rate.') parser.add_argument('--save_folder', default=r'', help='Location to save checkpoint models') parser.add_argument('--pretrained_model', default='', help='no pretrain')

另外,我是没加载预训练权重的,一开始训不好,后来发现调好learning_rate和lr_schedule这两个参数,一般都能训到不错的分数(93+)。

三、验证

在tools下的test_lprnet.py,主要配置:

def get_parser(): parser = argparse.ArgumentParser(description='parameters to train net') parser.add_argument('--img_size', default=[94, 24], help='the image size') parser.add_argument('--test_img_dirs', default=r"", help='the test images path') parser.add_argument('--dropout_rate', default=0, help='dropout rate.') parser.add_argument('--lpr_max_len', default=8, help='license plate number max length.') parser.add_argument('--test_batch_size', default=100, help='testing batch size.') parser.add_argument('--phase_train', default=False, type=bool, help='train or test phase flag.') parser.add_argument('--num_workers', default=0, type=int, help='Number of workers used in dataloading') parser.add_argument('--cuda', default=True, type=bool, help='Use cuda to train model') parser.add_argument('--show', default=False, type=bool, help='show test image and its predict result or not.') parser.add_argument('--pretrained_model', default=r'', help='pretrained base model')

LPRNet算法性能:

model数据集epochsaccsizeLPRNetval10094.331.7MLPRNettest10094.301.7M

整个模型(YOLOv5+LPRNet)速度:47.6FPS(970 GPU)

四、测试结果

请添加图片描述 请添加图片描述 当然也有检测的不好的: 请添加图片描述

五、推理代码

main.py

import argparse import torch.backends.cudnn as cudnn from models.experimental import * from utils.datasets import * from utils.utils import * from models.LPRNet import * def detect(save_img=False): classify, out, source, det_weights, rec_weights, view_img, save_txt, imgsz = \ opt.classify, opt.output, opt.source, opt.det_weights, opt.rec_weights, opt.view_img, opt.save_txt, opt.img_size webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt') # Initialize device = torch_utils.select_device(opt.device) if os.path.exists(out): shutil.rmtree(out) # delete rec_result folder os.makedirs(out) # make new rec_result folder half = device.type != 'cpu' # half precision only supported on CUDA # Load yolov5 model model = attempt_load(det_weights, map_location=device) # load FP32 model print("load det pretrained model successful!") imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size if half: model.half() # to FP16 # Second-stage classifier 也就是rec 字符识别 if classify: modelc = LPRNet(lpr_max_len=8, phase=False, class_num=len(CHARS), dropout_rate=0).to(device) modelc.load_state_dict(torch.load(rec_weights, map_location=torch.device('cpu'))) print("load rec pretrained model successful!") modelc.to(device).eval() # Set Dataloader vid_path, vid_writer = None, None if webcam: view_img = True cudnn.benchmark = True # set True to speed up constant image size demo dataset = LoadStreams(source, img_size=imgsz) else: save_img = True dataset = LoadImages(source, img_size=imgsz) # Get names and colors names = model.module.names if hasattr(model, 'module') else model.names colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))] # Run demo t0 = time.time() img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once for path, img, im0s, vid_cap in dataset: img = torch.from_numpy(img).to(device) img = img.half() if half else img.float() # uint8 to fp16/32 img /= 255.0 # 0 - 255 to 0.0 - 1.0 if img.ndimension() == 3: img = img.unsqueeze(0) # Inference t1 = torch_utils.time_synchronized() pred = model(img, augment=opt.augment)[0] # Apply NMS pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) t2 = torch_utils.time_synchronized() # Apply Classifier if classify: pred, plat_num = apply_classifier(pred, modelc, img, im0s) # Process detections for i, det in enumerate(pred): # detections per image if webcam: # batch_size >= 1 p, s, im0 = path[i], '%g: ' % i, im0s[i].copy() else: p, s, im0 = path, '', im0s save_path = str(Path(out) / Path(p).name) txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '') s += '%gx%g ' % img.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh if det is not None and len(det): # Rescale boxes from img_size to im0 size det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # Print results for c in det[:, 5].unique(): n = (det[:, 5] == c).sum() # detections per class s += '%g %ss, ' % (n, names[int(c)]) # add to string # Write results for de, lic_plat in zip(det, plat_num): # xyxy,conf,cls,lic_plat=de[:4],de[4],de[5],de[6:] *xyxy, conf, cls=de if save_txt: # Write to file xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh with open(txt_path + '.txt', 'a') as f: f.write(('%g ' * 5 + '\n') % (cls, xywh)) # label format if save_img or view_img: # Add bbox to image # label = '%s %.2f' % (names[int(cls)], conf) lb = "" for a,i in enumerate(lic_plat): # if a ==0: # continue lb += CHARS[int(i)] label = '%s %.2f' % (lb, conf) im0=plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) # Print time (demo + NMS) print('%sDone. (%.3fs)' % (s, t2 - t1)) # Stream results if view_img: cv2.imshow(p, im0) if cv2.waitKey(1) == ord('q'): # q to quit raise StopIteration # Save results (image with detections) if save_img: if dataset.mode == 'images': cv2.imwrite(save_path, im0) else: if vid_path != save_path: # new video vid_path = save_path if isinstance(vid_writer, cv2.VideoWriter): vid_writer.release() # release previous video writer fourcc = 'mp4v' # rec_result video codec fps = vid_cap.get(cv2.CAP_PROP_FPS) w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h)) vid_writer.write(im0) if save_txt or save_img: print('Results saved to %s' % os.getcwd() + os.sep + out) if platform == 'darwin': # MacOS os.system('open ' + save_path) print('Done. (%.3fs)' % (time.time() - t0)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--classify', nargs='+', type=str, default=True, help='True rec') parser.add_argument('--det-weights', nargs='+', type=str, default='./weights/yolov5_best.pt', help='model.pt path(s)') parser.add_argument('--rec-weights', nargs='+', type=str, default='./weights/lprnet_best.pth', help='model.pt path(s)') parser.add_argument('--source', type=str, default='./demo/images/', help='source') # file/folder, 0 for webcam parser.add_argument('--rec_result', type=str, default='demo/rec_result', help='rec_result folder') # rec_result folder parser.add_argument('--img-size', type=int, default=640, help='demo size (pixels)') parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold') parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--view-img', action='store_true', help='display results') parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') parser.add_argument('--classes', nargs='+', type=int, help='filter by class') parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') parser.add_argument('--augment', action='store_true', help='augmented demo') parser.add_argument('--update', action='store_true', help='update all models') opt = parser.parse_args() print(opt) with torch.no_grad(): if opt.update: # update all models (to fix SourceChangeWarning) for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov3-spp.pt']: detect() create_pretrained(opt.weights, opt.weights) else: detect() Reference

CSDN: linux-mobaxterm-yolov5训练数据集ccpd–无数踩雷后

Github: https://github.com/ultralytics/yolov5

Github: https://github.com/sirius-ai/LPRNet_Pytorch

Gitee: https://gitee.com/reason1251326862/plate_classification Github:https://github.com/kiloGrand/License-Plate-Recognition



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有