当前位置:   article > 正文

Python+Yolov5果树上的水果(苹果)检测识别_pytorch 水果识别案例源码

pytorch 水果识别案例源码

程序示例精选

Python+Yolov5果树上的水果(苹果)检测识别

如需安装运行环境或远程调试,见文章底部个人QQ名片,由专业技术人员远程协助!

前言

这篇博客针对<<Python+Yolov5果树上的水果(苹果)检测识别>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


文章目录

一、所需工具软件

二、使用步骤

        1. 引入库

        2. 代码实现

        3. 运行结果

三、在线协助

一、所需工具软件

1. Python,Pycharm

2. Yolov5

二、使用步骤

1.引入库

  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, non_max_suppression, apply_classifier, \
  11. scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
  12. from utils.plots import plot_one_box
  13. from utils.torch_utils import select_device, load_classifier, time_synchronized

2. 代码实现

代码如下:

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

3. 运行结果

 

三、在线协助:

如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!
1)远程安装运行环境,代码调试
2)Qt, C++, Python入门指导
3)界面美化
4)软件制作

博主推荐文章:python人脸识别统计人数qt窗体-CSDN博客

博主推荐文章:Python Yolov5火焰烟雾识别源码分享-CSDN博客

                         Python OpenCV识别行人入口进出人数统计_python识别人数-CSDN博客

个人博客主页:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

博主所有文章点这里:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

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

闽ICP备14008679号