当前位置:   article > 正文

Python+Yolov8目标识别特征检测_yolov8 python

yolov8 python

Yolov8目标识别特征检测

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

前言

这篇博客针对<<Yolov8目标识别特征检测>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。

文章目录

一、所需工具软件

二、使用步骤

1. 引入库

2. 识别图像特征

3. 参数设置

4. 运行结果

三、在线协助

一、所需工具软件

1. Pycharm, Python

2. Yolov8, OpenCV

二、使用步骤

1.引入库

代码如下(示例):

  1. import torch
  2. from ultralytics.yolo.engine.predictor import BasePredictor
  3. from ultralytics.yolo.engine.results import Results
  4. from ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops
  5. from ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box

2.识别图像特征

代码如下(示例):

  1. class DetectionPredictor(BasePredictor):
  2. def get_annotator(self, img):
  3. return Annotator(img, line_width=self.args.line_thickness, example=str(self.model.names))
  4. def preprocess(self, img):
  5. img = torch.from_numpy(img).to(self.model.device)
  6. img = img.half() if self.model.fp16 else img.float() # uint8 to fp16/32
  7. img /= 255 # 0 - 255 to 0.0 - 1.0
  8. return img
  9. def postprocess(self, preds, img, orig_img):
  10. preds = ops.non_max_suppression(preds,
  11. self.args.conf,
  12. self.args.iou,
  13. agnostic=self.args.agnostic_nms,
  14. max_det=self.args.max_det,
  15. classes=self.args.classes)
  16. results = []
  17. for i, pred in enumerate(preds):
  18. orig_img = orig_img[i] if isinstance(orig_img, list) else orig_img
  19. shape = orig_img.shape
  20. pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], shape).round()
  21. results.append(Results(boxes=pred, orig_img=orig_img, names=self.model.names))
  22. return results
  23. def write_results(self, idx, results, batch):
  24. p, im, im0 = batch
  25. log_string = ''
  26. if len(im.shape) == 3:
  27. im = im[None] # expand for batch dim
  28. self.seen += 1
  29. imc = im0.copy() if self.args.save_crop else im0
  30. if self.source_type.webcam or self.source_type.from_img: # batch_size >= 1
  31. log_string += f'{idx}: '
  32. frame = self.dataset.count
  33. else:
  34. frame = getattr(self.dataset, 'frame', 0)
  35. self.data_path = p
  36. self.txt_path = str(self.save_dir / 'labels' / p.stem) + ('' if self.dataset.mode == 'image' else f'_{frame}')
  37. log_string += '%gx%g ' % im.shape[2:] # print string
  38. self.annotator = self.get_annotator(im0)
  39. det = results[idx].boxes # TODO: make boxes inherit from tensors
  40. if len(det) == 0:
  41. return log_string
  42. for c in det.cls.unique():
  43. n = (det.cls == c).sum() # detections per class
  44. log_string += f"{n} {self.model.names[int(c)]}{'s' * (n > 1)}, "
  45. # write
  46. for d in reversed(det):
  47. cls, conf = d.cls.squeeze(), d.conf.squeeze()
  48. if self.args.save_txt: # Write to file
  49. line = (cls, *(d.xywhn.view(-1).tolist()), conf) \
  50. if self.args.save_conf else (cls, *(d.xywhn.view(-1).tolist())) # label format
  51. with open(f'{self.txt_path}.txt', 'a') as f:
  52. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  53. if self.args.save or self.args.save_crop or self.args.show: # Add bbox to image
  54. c = int(cls) # integer class
  55. name = f'id:{int(d.id.item())} {self.model.names[c]}' if d.id is not None else self.model.names[c]
  56. label = None if self.args.hide_labels else (name if self.args.hide_conf else f'{name} {conf:.2f}')
  57. self.annotator.box_label(d.xyxy.squeeze(), label, color=colors(c, True))
  58. if self.args.save_crop:
  59. save_one_box(d.xyxy,
  60. imc,
  61. file=self.save_dir / 'crops' / self.model.model.names[c] / f'{self.data_path.stem}.jpg',
  62. BGR=True)
  63. return log_string

3.参数定义

代码如下(示例):

  1. if __name__ == '__main__':
  2. parser = argparse.ArgumentParser()
  3. parser.add_argument('--weights', nargs='+', type=str, default='yolov5_best_road_crack_recog.pt', help='model.pt path(s)')
  4. parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
  5. parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
  6. parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
  7. parser.add_argument('--view-img', action='store_true', help='display results')
  8. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  9. parser.add_argument('--classes', nargs='+', type=int, default='0', help='filter by class: --class 0, or --class 0 2 3')
  10. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  11. parser.add_argument('--augment', action='store_true', help='augmented inference')
  12. parser.add_argument('--update', action='store_true', help='update all models')
  13. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  14. parser.add_argument('--name', default='exp', help='save results to project/name')
  15. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  16. opt = parser.parse_args()

4.运行结果如下

三、在线协助:

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

博主推荐文章:https://blog.csdn.net/alicema1111/article/details/123851014

个人博客主页:https://blog.csdn.net/alicema1111?type=blog

博主所有文章点这里:https://blog.csdn.net/alicema1111?type=blog

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

闽ICP备14008679号