当前位置:   article > 正文

python+torch+yolov卷积神经网络训练识别人脸口罩_if webcam: p, s, im0, frame = path[i], '%g: ' % i,

if webcam: p, s, im0, frame = path[i], '%g: ' % i, im0s[

python+torch+yolov卷积神经网络训练识别人脸口罩

如需安装运行环境或远程调试,可加QQ905733049, 或QQ2945218359由专业技术人员远程协助!

运行结果如下:

主代码如下:

  1. import argparse
  2. import time
  3. from pathlib import Path
  4. import cv2
  5. import torch
  6. import torch.backends.cudnn as cudnn
  7. from numpy import random
  8. from models.experimental import attempt_load
  9. from utils.datasets import LoadStreams, LoadImages
  10. from utils.general import check_img_size, check_requirements, check_imshow,
  11. def detect(save_img=False):
  12. source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
  13. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  14. ('rtsp://', 'rtmp://', 'http://'))
  15. # Directories
  16. save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
  17. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  18. # Initialize
  19. set_logging()
  20. device = select_device(opt.device)
  21. half = device.type != 'cpu' # half precision only supported on CUDA
  22. # Load model
  23. model = attempt_load(weights, map_location=device) # load FP32 model
  24. stride = int(model.stride.max()) # model stride
  25. imgsz = check_img_size(imgsz, s=stride) # check img_size
  26. if half:
  27. model.half() # to FP16
  28. # Second-stage classifier
  29. classify = False
  30. if classify:
  31. modelc = load_classifier(name='resnet101', n=2) # initialize
  32. modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
  33. # Set Dataloader
  34. vid_path, vid_writer = None, None
  35. if webcam:
  36. view_img = check_imshow()
  37. cudnn.benchmark = True # set True to speed up constant image size inference
  38. dataset = LoadStreams(source, img_size=imgsz, stride=stride)
  39. else:
  40. save_img = True
  41. dataset = LoadImages(source, img_size=imgsz, stride=stride)
  42. # Get names and colors
  43. names = model.module.names if hasattr(model, 'module') else model.names
  44. classes=opt.classes, agnostic=opt.agnostic_nms)
  45. t2 = time_synchronized()
  46. # Apply Classifier
  47. if classify:
  48. pred = apply_classifier(pred, modelc, img, im0s)
  49. # Process detections
  50. for i, det in enumerate(pred): # detections per image
  51. if webcam: # batch_size >= 1
  52. p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
  53. else:
  54. p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
  55. p = Path(p) # to Path
  56. save_path = str(save_dir / p.name) # img.jpg
  57. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  58. s += '%gx%g ' % img.shape[2:] # print string
  59. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  60. if len(det):
  61. # Rescale boxes from img_size to im0 size
  62. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  63. # Print results
  64. for c in det[:, -1].unique():
  65. n = (det[:, -1] == c).sum() # detections per class
  66. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  67. # Write results
  68. for *xyxy, conf, cls in reversed(det):
  69. if save_txt: # Write to file
  70. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  71. line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
  72. with open(txt_path + '.txt', 'a') as f:
  73. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  74. if save_img or view_img: # Add bbox to image
  75. label = f'{names[int(cls)]} {conf:.2f}'
  76. plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
  77. # Print time (inference + NMS)
  78. print(f'{s}Done. ({t2 - t1:.3f}s)')
  79. # Stream results
  80. if view_img:
  81. cv2.imshow(str(p), im0)
  82. cv2.waitKey(1) # 1 millisecond
  83. # Save results (image with detections)
  84. if save_img:
  85. if dataset.mode == 'image':
  86. cv2.imwrite(save_path, im0)
  87. else: # 'video'
  88. if vid_path != save_path: # new video
  89. vid_path = save_path
  90. if isinstance(vid_writer, cv2.VideoWriter):
  91. vid_writer.release() # release previous video writer
  92. fourcc = 'mp4v' # output video codec
  93. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  94. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  95. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  96. vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
  97. vid_writer.write(im0)
  98. if save_txt or save_img:
  99. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  100. print(f"Results saved to {save_dir}{s}")
  101. print(f'Done. ({time.time() - t0:.3f}s)')
  102. if __name__ == '__main__':
  103. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  104. parser.add_argument('--view-img', action='store_true', help='display results')
  105. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  106. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  107. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  108. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  109. parser.add_argument('--augment', action='store_true', help='augmented inference')
  110. parser.add_argument('--update', action='store_true', help='update all models')
  111. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  112. parser.add_argument('--name', default='exp', help='save results to project/name')
  113. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  114. opt = parser.parse_args()
  115. print("----")
  116. print(opt)
  117. check_requirements()
  118. with torch.no_grad():
  119. if opt.update: # update all models (to fix SourceChangeWarning)
  120. for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
  121. detect()
  122. strip_optimizer(opt.weights)
  123. else:
  124. detect()

运行结果如下:

 

C++学习参考实例

C++实现图形界面五子棋游戏源码:

https://blog.csdn.net/alicema1111/article/details/90035420

C++实现图形界面五子棋游戏源码2:

https://blog.csdn.net/alicema1111/article/details/106479579

C++ OpenCV相片视频人脸识别统计人数:

https://blog.csdn.net/alicema1111/article/details/105833928

VS2017+PCL开发环境配置:

https://blog.csdn.net/alicema1111/article/details/106877145

VS2017+Qt+PCL点云开发环境配置:

https://blog.csdn.net/alicema1111/article/details/105433636

C++ OpenCV汽车检测障碍物与测距:

https://blog.csdn.net/alicema1111/article/details/105833449

Windows VS2017安装配置PCL点云库:

https://blog.csdn.net/alicema1111/article/details/105111110

VS+VTK+Dicom(dcm)+CT影像切片窗体界面显示源码

https://blog.csdn.net/alicema1111/article/details/106994839

 

Python学习参考实例

Python相片更换背景颜色qt窗体程序:

https://blog.csdn.net/alicema1111/article/details/106919140

OpenCV汽车识别检测数量统计:

https://blog.csdn.net/alicema1111/article/details/106597260

OpenCV视频识别检测人数跟踪统计:

https://blog.csdn.net/alicema1111/article/details/106113042

OpenCV米粒检测数量统计:

https://blog.csdn.net/alicema1111/article/details/106089697

opencv人脸识别与变形哈哈镜:

https://blog.csdn.net/alicema1111/article/details/105833123

OpenCV人脸检测打卡系统:

https://blog.csdn.net/alicema1111/article/details/105315066

Python+OpenCV摄像头人脸识别:

https://blog.csdn.net/alicema1111/article/details/105107286

Python+Opencv识别视频统计人数:

https://blog.csdn.net/alicema1111/article/details/103804032

Python+OpenCV图像人脸识别人数统计

https://blog.csdn.net/alicema1111/article/details/105378639

python人脸头发身体部位识别人数统计

https://blog.csdn.net/alicema1111/article/details/116424942

 

PHP网页框架

PHP Laravel框架安装与配置后台管理前台页面显示:

https://blog.csdn.net/alicema1111/article/details/106686523

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/428737
推荐阅读
相关标签
  

闽ICP备14008679号