0


Mac 电脑配置yolov8运行环境实现目标追踪、计数、画出轨迹、多线程

🥇 版权: 本文由【墨理学AI】原创首发、各位读者大大、敬请查阅、感谢三连
🎉 **声明:**作为全网 AI 领域 干货最多的博主之一,❤️ 不负光阴不负卿 ❤️

0-9

文章目录

📙 Mac 电脑 配置 yolov8 环境

  • YOLO 推理测试、小数据集训练,基础版 Mac 即可满足
  • 博主这里代码运行的 Mac 版本为 M1 Pro
  1. conda 环境搭建步骤如下
  1. conda create -n yolopy39 python=3.9
  2. conda activate yolopy39
  3. pip3 install torch torchvision torchaudio
  4. # ultralytics 对 opencv-python 的版本需求如下
  5. pip3 install opencv-python>=4.6.0# 因此我选择安装的版本如下
  6. pip3 install opencv-python==4.6.0.66
  7. cd Desktop
  8. mkdir moli
  9. cd moli
  10. git clone https://github.com/ultralytics/ultralytics.git
  11. pip install -e .
  12. pwd
  13. /Users/moli/Desktop/moli/ultralytics

📙 代码运行

  1. 代码运行主要参考如下两个官方教程
推理测试
  1. yolo predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'
  1. yolo predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'# 输出如下
  2. Matplotlib is building the font cache; this may take a moment.
  3. Downloading https://github.com/ultralytics/assets/releases/download/v8.2.0/yolov8n.pt to 'yolov8n.pt'...100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████|6.25M/6.25M [01:34<00:00,69.6kB/s]
  4. Ultralytics YOLOv8.2.77 🚀 Python-3.9.19 torch-2.2.2 CPU (Apple M1 Pro)[W NNPACK.cpp:64] Could not initialize NNPACK! Reason: Unsupported hardware.
  5. YOLOv8n summary (fused):168 layers,3,151,904 parameters,0 gradients,8.7 GFLOPs
  6. Downloading https://ultralytics.com/images/bus.jpg to 'bus.jpg'...100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 134k/134k [00:00<00:00, 470kB/s]
  7. image 1/1/Users/moli/Desktop/moli/ultralytics/bus.jpg: 640x480 4 persons,1 bus,1 stop sign,221.3ms
  8. Speed:5.8ms preprocess,221.3ms inference,4.0ms postprocess per image at shape (1,3,640,480)
  9. Results saved to /Users/moli/Desktop/moli/ultralytics/runs/detect/predict
模型训练 - 转 onnx
  1. vim train_test.py
  1. from ultralytics import YOLO
  2. # Load a model
  3. model = YOLO("yolov8n.yaml")# build a new model from scratch
  4. model = YOLO("yolov8n.pt")# load a pretrained model (recommended for training)# Use the model
  5. model.train(data="coco8.yaml", epochs=3)# train the model
  6. metrics = model.val()# evaluate model performance on the validation set
  7. results = model("https://ultralytics.com/images/bus.jpg")# predict on an image# 转换 onnx 也是封装好的模块,这里调用传参即可
  8. path = model.export(format="onnx")# export the model to ONNX format
  1. 运行输出如下
  1. python train_test.py
  2. [W NNPACK.cpp:64] Could not initialize NNPACK! Reason: Unsupported hardware.
  3. Ultralytics YOLOv8.2.77 🚀 Python-3.9.19 torch-2.2.2 CPU (Apple M1 Pro)
  4. engine/trainer: task=detect, mode=train, model=yolov8n.pt, data=coco8.yaml, epochs=3, time=None, patience=100, batch=16, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=train, exist_ok=False, pretrained=True, optimizer=auto, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, amp=True, fraction=1.0, profile=False, freeze=None, multi_scale=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, vid_stride=1, stream_buffer=False, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, embed=None, show=False, save_frames=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, show_boxes=True, line_width=None,format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, bgr=0.0, mosaic=1.0, mixup=0.0, copy_paste=0.0, auto_augment=randaugment, erasing=0.4, crop_fraction=1.0, cfg=None, tracker=botsort.yaml, save_dir=/Users/moli/Desktop/moli/ultralytics/runs/detect/train
  5. Dataset 'coco8.yaml' images not found ⚠️, missing path '/Users/moli/Desktop/moli/datasets/coco8/images/val'
  6. Downloading https://ultralytics.com/assets/coco8.zip to '/Users/moli/Desktop/moli/datasets/coco8.zip'...100%|███████████████████████████████████████████████████████████████████████████████████████████| 433k/433k [00:03<00:00, 135kB/s]
  7. Unzipping /Users/moli/Desktop/moli/datasets/coco8.zip to /Users/moli/Desktop/moli/datasets/coco8...:100%|██████████|25/25[00:00
  8. Dataset download success (5.4s), saved to /Users/moli/Desktop/moli/datasets
  9. ......
  10. Logging results to /Users/moli/Desktop/moli/ultralytics/runs/detect/train
  11. Starting training for3 epochs...
  12. Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size
  13. 1/3 0G 1.4122.8151.75522640:100%|██████████|1/1[00:01<00:00,1.90s/it]
  14. Class Images Instances Box(P R mAP50 mAP50-95):100%|██████████|1/1[00:00<00:00,1.30all4170.6130.8830.8880.616
  15. Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size
  16. 2/3 0G 1.2492.6211.44123640:100%|██████████|1/1[00:01<00:00,1.51s/it]
  17. Class Images Instances Box(P R mAP50 mAP50-95):100%|██████████|1/1[00:00<00:00,2.24all4170.5980.8960.8880.618
  18. Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size
  19. 3/3 0G 1.1424.2211.49516640:100%|██████████|1/1[00:01<00:00,1.50s/it]
  20. Class Images Instances Box(P R mAP50 mAP50-95):100%|██████████|1/1[00:00<00:00,2.06all4170.580.8330.8740.6133 epochs completed in0.002 hours.
  21. Optimizer stripped from/Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/last.pt,6.5MB
  22. Optimizer stripped from/Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/best.pt,6.5MB
  23. Validating /Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/best.pt...
  24. Ultralytics YOLOv8.2.77 🚀 Python-3.9.19 torch-2.2.2 CPU (Apple M1 Pro)
  25. Model summary (fused):168 layers,3,151,904 parameters,0 gradients,8.7 GFLOPs
  26. Class Images Instances Box(P R mAP50 mAP50-95):100%|██████████|1/1[00:00<00:00,1.72all4170.5990.8980.8880.618
  27. person 3100.6470.50.520.29
  28. dog 110.31510.9950.597
  29. horse 120.68910.9950.598
  30. elephant 120.6290.8870.8280.332
  31. umbrella 110.53910.9950.995
  32. potted plant 110.77410.9950.895
  33. Speed:4.2ms preprocess,134.0ms inference,0.0ms loss,0.8ms postprocess per image
  34. Results saved to /Users/moli/Desktop/moli/ultralytics/runs/detect/train
  35. Ultralytics YOLOv8.2.77 🚀 Python-3.9.19 torch-2.2.2 CPU (Apple M1 Pro)
  36. Model summary (fused):168 layers,3,151,904 parameters,0 gradients,8.7 GFLOPs
  37. val: Scanning /Users/moli/Desktop/moli/datasets/coco8/labels/val.cache...4 images,0 backgrounds,0 corrupt:100%|██████████|4/4
  38. Class Images Instances Box(P R mAP50 mAP50-95):100%|██████████|1/1[00:00<00:00,2.02all4170.5990.8980.8880.618
  39. person 3100.6470.50.520.29
  40. dog 110.31510.9950.597
  41. horse 120.68910.9950.598
  42. elephant 120.6290.8870.8280.332
  43. umbrella 110.53910.9950.995
  44. potted plant 110.77410.9950.895
  45. Speed:4.1ms preprocess,113.0ms inference,0.0ms loss,0.7ms postprocess per image
  46. Results saved to /Users/moli/Desktop/moli/ultralytics/runs/detect/train2
  47. image 1/1/Users/moli/Desktop/moli/ultralytics/ultralytics/assets/bus.jpg: 640x480 4 persons,1 bus,188.4ms
  48. Speed:3.9ms preprocess,188.4ms inference,1.0ms postprocess per image at shape (1,3,640,480)
  49. Ultralytics YOLOv8.2.77 🚀 Python-3.9.19 torch-2.2.2 CPU (Apple M1 Pro)# 开始模型转换
  50. PyTorch: starting from'/Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/best.pt'withinput shape (1,3,640,640) BCHW and output shape(s)(1,84,8400)(6.2 MB)
  51. requirements: Ultralytics requirement ['onnx>=1.12.0']not found, attempting AutoUpdate...
  52. Looking in indexes: http://pypi.douban.com/simple, http://mirrors.aliyun.com/pypi/simple/, https://pypi.tuna.tsinghua.edu.cn/simple/, http://pypi.mirrors.ustc.edu.cn/simple/
  53. Collecting onnx>=1.12.0
  54. Downloading http://mirrors.ustc.edu.cn/pypi/packages/4e/35/abbf2fa3dbb96b430f6e810e3fb7bc042ed150f371cb1aedb47052c40f8e/onnx-1.16.2-cp39-cp39-macosx_11_0_universal2.whl (16.5 MB)
  55. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 16.5/16.5 MB 11.4 MB/s eta 0:00:00
  56. Requirement already satisfied: numpy>=1.20in/Users/moli/opt/anaconda3/envs/yolopy39/lib/python3.9/site-packages (from onnx>=1.12.0)(1.26.4)
  57. Collecting protobuf>=3.20.2(from onnx>=1.12.0)
  58. Downloading http://mirrors.ustc.edu.cn/pypi/packages/ca/bc/bceb11aa96dd0b2ae7002d2f46870fbdef7649a0c28420f0abb831ee3294/protobuf-5.27.3-cp38-abi3-macosx_10_9_universal2.whl (412 kB)
  59. Installing collected packages: protobuf, onnx
  60. Successfully installed onnx-1.16.2 protobuf-5.27.3
  61. requirements: AutoUpdate success 22.0s, installed 1 package:['onnx>=1.12.0']
  62. requirements: ⚠️ Restart runtime or rerun command for updates to take effect
  63. ONNX: starting export with onnx 1.16.2 opset 17...
  64. ONNX: export success 24.4s, saved as'/Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/best.onnx'(12.2 MB)
  65. Export complete (26.1s)
  66. Results saved to /Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights
  67. Predict: yolo predict task=detect model=/Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/best.onnx imgsz=640
  68. Validate: yolo val task=detect model=/Users/moli/Desktop/moli/ultralytics/runs/detect/train/weights/best.onnx imgsz=640 data=/Users/moli/Desktop/moli/ultralytics/ultralytics/cfg/datasets/coco8.yaml
  69. Visualize: https://netron.app
  1. 可以看到运行成功、训练、转换 onnx 如下
  1. ls runs/detect/train/
  2. F1_curve.png R_curve.png confusion_matrix_normalized.png results.csv train_batch1.jpg val_batch0_pred.jpg
  3. PR_curve.png args.yaml labels.jpg results.png train_batch2.jpg weights
  4. P_curve.png confusion_matrix.png labels_correlogram.jpg train_batch0.jpg val_batch0_labels.jpg
  5. (yolopy39) moli@molideMacBook-Pro ultralytics % ls runs/detect/train/weights
  6. best.onnx best.pt last.pt
视频-目标检测
  1. cat yolov8_1.py
  2. from ultralytics import YOLO
  3. # Load an official or custom model
  4. model = YOLO("yolov8n.pt")# Load an official Detect model#model = YOLO("yolov8n-seg.pt") # Load an official Segment model#model = YOLO("yolov8n-pose.pt") # Load an official Pose model#model = YOLO("path/to/best.pt") # Load a custom trained model# Perform tracking with the model
  5. source ='video/people.mp4'
  6. results = model.track(source, show=True)# Tracking with default tracker
  1. 代码运行效果如下:

1-001

调用 Mac 电脑摄像头
  1. source = 0 即可
  1. from ultralytics import YOLO
  2. # Load an official or custom model
  3. model = YOLO("yolov8n.pt")# Load an official Detect model#source = 'video/people.mp4'
  4. source =0
  5. results = model.track(source, show=True)# Tracking with default tracker# results = model.track(source, show=True, tracker="bytetrack.yaml") # with ByteTrack
  1. 效果示例如下

1-0001

PersistingTracksLoop 持续目标跟踪
  1. vim yolov8PersistingTracksLoop.py
  1. import cv2
  2. from ultralytics import YOLO
  3. # Load the YOLOv8 model
  4. model = YOLO("yolov8n.pt")# Open the video file
  5. video_path ="./video/test_people.mp4"
  6. cap = cv2.VideoCapture(video_path)# Loop through the video frameswhile cap.isOpened():# Read a frame from the video
  7. success, frame = cap.read()if success:# Run YOLOv8 tracking on the frame, persisting tracks between frames
  8. results = model.track(frame, persist=True)# Visualize the results on the frame
  9. annotated_frame = results[0].plot()# Display the annotated frame
  10. cv2.imshow("YOLOv8 Tracking", annotated_frame)# Break the loop if 'q' is pressedif cv2.waitKey(1)&0xFF==ord("q"):breakelse:# Break the loop if the end of the video is reachedbreak# Release the video capture object and close the display window
  11. cap.release()
  12. cv2.destroyAllWindows()
  1. python3 yolov8PersistingTracksLoop.py 运行效果如下

2-0003

Plotting Tracks 画轨迹
  1. vim yolov8PlottingTracks.py
  1. from collections import defaultdict
  2. import cv2
  3. import numpy as np
  4. from ultralytics import YOLO
  5. # Load the YOLOv8 model
  6. model = YOLO("yolov8n.pt")# Open the video file
  7. video_path ="./video/test_people.mp4"
  8. cap = cv2.VideoCapture(video_path)# Store the track history
  9. track_history = defaultdict(lambda:[])# Loop through the video frameswhile cap.isOpened():# Read a frame from the video
  10. success, frame = cap.read()if success:# Run YOLOv8 tracking on the frame, persisting tracks between frames
  11. results = model.track(frame, persist=True)# Get the boxes and track IDs
  12. boxes = results[0].boxes.xywh.cpu()
  13. track_ids = results[0].boxes.id.int().cpu().tolist()# Visualize the results on the frame
  14. annotated_frame = results[0].plot()# Plot the tracksfor box, track_id inzip(boxes, track_ids):
  15. x, y, w, h = box
  16. track = track_history[track_id]
  17. track.append((float(x),float(y)))# x, y center pointiflen(track)>30:# retain 90 tracks for 90 frames
  18. track.pop(0)# Draw the tracking lines
  19. points = np.hstack(track).astype(np.int32).reshape((-1,1,2))
  20. cv2.polylines(annotated_frame,[points], isClosed=False, color=(230,230,230), thickness=10)# Display the annotated frame
  21. cv2.imshow("YOLOv8 Tracking", annotated_frame)# Break the loop if 'q' is pressedif cv2.waitKey(1)&0xFF==ord("q"):breakelse:# Break the loop if the end of the video is reachedbreak# Release the video capture object and close the display window
  22. cap.release()
  23. cv2.destroyAllWindows()
  1. python3 yolov8PlottingTracks.py 运行效果如下,可以看看行人后有轨迹

2-0005

Multithreaded Tracking - 多线程运行示例
  1. vim yolov8MultithreadedTracking.py
  • 这里加载两个模型,运行两个线程,出现线程拥挤、导致无法弹窗,代码需要进一步修改
  1. import threading
  2. import cv2
  3. from ultralytics import YOLO
  4. defrun_tracker_in_thread(filename, model, file_index):"""
  5. Runs a video file or webcam stream concurrently with the YOLOv8 model using threading.
  6. This function captures video frames from a given file or camera source and utilizes the YOLOv8 model for object
  7. tracking. The function runs in its own thread for concurrent processing.
  8. Args:
  9. filename (str): The path to the video file or the identifier for the webcam/external camera source.
  10. model (obj): The YOLOv8 model object.
  11. file_index (int): An index to uniquely identify the file being processed, used for display purposes.
  12. Note:
  13. Press 'q' to quit the video display window.
  14. """
  15. video = cv2.VideoCapture(filename)# Read the video filewhileTrue:
  16. ret, frame = video.read()# Read the video frames# Exit the loop if no more frames in either videoifnot ret:break# Track objects in frames if available
  17. results = model.track(frame, persist=True)
  18. res_plotted = results[0].plot()
  19. cv2.imshow(f"Tracking_Stream_{file_index}", res_plotted)
  20. key = cv2.waitKey(1)if key ==ord("q"):break# Release video sources
  21. video.release()# Load the models
  22. model1 = YOLO("yolov8n.pt")
  23. model2 = YOLO("yolov8n-seg.pt")# Define the video files for the trackers
  24. video_file1 ="video/test_people.mp4"# Path to video file, 0 for webcam#video_file2 = 'video/test_traffic.mp4' # Path to video file, 0 for webcam, 1 for external camera
  25. video_file2 =0# Create the tracker threads
  26. tracker_thread1 = threading.Thread(target=run_tracker_in_thread, args=(video_file1, model1,1), daemon=True)
  27. tracker_thread2 = threading.Thread(target=run_tracker_in_thread, args=(video_file2, model2,2), daemon=True)# Start the tracker threads
  28. tracker_thread1.start()
  29. tracker_thread2.start()# Wait for the tracker threads to finish
  30. tracker_thread1.join()
  31. tracker_thread2.join()# Clean up and close windows
  32. cv2.destroyAllWindows()

📙 YOLO 系列实战博文汇总如下


🟦 YOLO 理论讲解学习篇
🟧 Yolov5 系列
  • 💜 YOLOv5 环境搭建 | coco128 训练示例 |❤️ 详细记录❤️ |【YOLOv5】
  • 💜 YOLOv5 COCO数据集 训练 | 【YOLOv5 训练】
🟨 YOLOX 系列
  • 💛 YOLOX 环境搭建 | 测试 | COCO训练复现 【YOLOX 实战】
  • 💛 YOLOX (pytorch)模型 ONNX export | 运行推理【YOLOX 实战二】
  • 💛 YOLOX (pytorch)模型 转 ONNX 转 ncnn 之运行推理【YOLOX 实战三】
  • 💛 YOLOX (pytorch)模型 转 tensorRT 之运行推理【YOLOX 实战四】
🟦 Yolov3 系列
  • 💙 yolov3(darknet )训练 - 测试 - 模型转换❤️darknet 转 ncnn 之C++运行推理❤️【yolov3 实战一览】
  • 💙 YOLOv3 ncnn 模型 yolov3-spp.cpp ❤️【YOLOv3之Ncnn推理实现———附代码】
🟨 YOLOX 系列
  • Ubuntu 22.04 搭建 yolov8 环境 运行示例代码(轨迹跟踪、过线 人数统计、目标热力图)
🟦 持续补充更新

❤️ 人生苦短, 欢迎和墨理一起学AI


  • 🎉 作为全网 AI 领域 干货最多的博主之一,❤️ 不负光阴不负卿 ❤️
  • ❤️ 如果文章对你有些许帮助、蟹蟹各位读者大大点赞、评论鼓励博主的每一分认真创作

9-9

标签: macos YOLO yolov8

本文转载自: https://blog.csdn.net/sinat_28442665/article/details/141199709
版权归原作者 墨理学AI 所有, 如有侵权,请联系我们删除。

“Mac 电脑配置yolov8运行环境实现目标追踪、计数、画出轨迹、多线程”的评论:

还没有评论