Hướng dẫn toàn diện về Ultralytics YOLO
Các hướng dẫn Ultralytics YOLO bao quát mọi giai đoạn của dự án vision AI, từ huấn luyện và dự đoán đến triển khai. Được xây dựng trên PyTorch, YOLO kết hợp tốc độ và độ chính xác cho phát hiện đối tượng theo thời gian thực và các tác vụ thị giác khác.
Dù bạn là người mới bắt đầu hay chuyên gia về deep learning, các hướng dẫn này cung cấp chỉ dẫn thực tế để triển khai và tối ưu hóa YOLO cho các dự án thị giác máy tính của bạn.
Xem: Tổng quan về hướng dẫn Ultralytics YOLO26
Hướng dẫn#
Các hướng dẫn được nhóm theo từng giai đoạn của dự án — từ thiết lập môi trường và chuẩn bị dữ liệu đến huấn luyện, đánh giá, triển khai, tối ưu hóa inference và phần cứng biên — để bạn có thể chuyển thẳng đến bước đang thực hiện.
Bắt đầu & lập kế hoạch#
- Hướng dẫn bắt đầu nhanh với Conda: Hướng dẫn từng bước thiết lập môi trường Conda cho Ultralytics. Tìm hiểu cách cài đặt và bắt đầu sử dụng package Ultralytics hiệu quả với Conda.
- Hướng dẫn bắt đầu nhanh với Docker: Hướng dẫn đầy đủ về cách thiết lập và sử dụng model Ultralytics YOLO với Docker. Tìm hiểu cách cài đặt Docker, quản lý hỗ trợ GPU và chạy model YOLO trong các container độc lập để đảm bảo quy trình phát triển và triển khai nhất quán.
- Hướng dẫn bắt đầu nhanh với AzureML: Bắt đầu sử dụng model Ultralytics YOLO trên nền tảng Machine Learning Azure của Microsoft. Tìm hiểu cách huấn luyện, triển khai và mở rộng quy mô các dự án phát hiện đối tượng trên cloud.
- Hướng dẫn bắt đầu nhanh với Modal: Chạy Ultralytics YOLO26 trên nền tảng cloud serverless của Modal, bao gồm xác thực, inference GPU và các job huấn luyện với bộ nhớ lưu trữ liên tục — không cần quản lý hạ tầng.
- Xác định mục tiêu cho dự án computer vision: Tìm hiểu từng bước cách xác định hiệu quả các mục tiêu rõ ràng và có thể đo lường cho dự án computer vision của bạn. Tìm hiểu tầm quan trọng của việc xác định rõ bài toán và cách việc này tạo lộ trình cho dự án.
- Các bước thực hiện dự án computer vision: Tìm hiểu các bước chính trong một dự án computer vision, bao gồm xác định mục tiêu, chọn model, chuẩn bị dữ liệu và đánh giá kết quả.
- Giải thích kiến trúc YOLO: Theo dõi quá trình phát triển của kiến trúc YOLO từ YOLOv3 đến YOLO26 qua backbone, neck và detection head, bao gồm C2f, C3k2, cơ chế attention C2PSA, thiết kế không dùng anchor và không dùng NMS.
Chuẩn bị dữ liệu#
- Thu thập và gán nhãn dữ liệu: Khám phá các công cụ, kỹ thuật và phương pháp tốt nhất để thu thập và gán nhãn dữ liệu, tạo đầu vào chất lượng cao cho model computer vision.
- Tiền xử lý dữ liệu đã gán nhãn: Tìm hiểu cách tiền xử lý dữ liệu cho computer vision với YOLO26, bao gồm thay đổi kích thước ảnh, chuẩn hóa, chia tập dữ liệu, tăng cường dữ liệu và phân tích dữ liệu khám phá (EDA).
- Tăng cường dữ liệu YOLO: Khám phá đầy đủ các kỹ thuật tăng cường dữ liệu trong YOLO, từ các phép biến đổi cơ bản đến chiến lược nâng cao nhằm cải thiện độ bền vững và hiệu suất của model.
- Chuyển đổi COCO sang YOLO: Hướng dẫn đầy đủ về cách chuyển đổi annotation COCO JSON sang định dạng YOLO để huấn luyện. Nội dung bao gồm phát hiện, phân đoạn và keypoint, cùng với ánh xạ class ID và các lỗi thường gặp khi chuyển đổi.
- Huấn luyện với COCO JSON: Huấn luyện YOLO trực tiếp trên annotation COCO JSON mà không cần chuyển sang định dạng YOLO, bằng cách sử dụng class dataset và trainer tùy chỉnh.
Huấn luyện & fine-tune#
- Chia ảnh độ phân giải cao theo ô: Huấn luyện, xác thực và dự đoán trên ảnh độ phân giải cao bằng cách chia ảnh thành các ô cố định cho mọi tác vụ thị giác.
- Mẹo huấn luyện model: Tìm hiểu các mẹo tối ưu hóa kích thước batch, sử dụng độ chính xác hỗn hợp, áp dụng trọng số pretrained và nhiều nội dung khác để huấn luyện model thị giác máy tính hiệu quả hơn.
- Fine-tune YOLO trên dữ liệu tùy chỉnh: Hướng dẫn đầy đủ về cách fine-tune YOLO26 trên dataset tùy chỉnh với trọng số pretrained, bao gồm transfer learning, đóng băng layer, lựa chọn optimizer, huấn luyện hai giai đoạn và khắc phục sự cố.
- Công thức huấn luyện YOLO26: Tài liệu đầy đủ về hyperparameter, pipeline tăng cường dữ liệu và thiết lập optimizer được sử dụng để huấn luyện các checkpoint YOLO26 base chính thức trên COCO, kèm hướng dẫn fine-tune thực tế.
- Tinh chỉnh hyperparameter: Tìm hiểu cách tối ưu hóa model YOLO bằng cách fine-tune hyperparameter thông qua class Tuner và các thuật toán tiến hóa di truyền.
- Chưng cất tri thức: Tìm hiểu cách cải thiện hiệu năng model bằng cách truyền tri thức từ model teacher lớn hơn sang model student nhỏ hơn thông qua phương pháp chưng cất dựa trên feature.
- Kiểm định chéo K-Fold: Tìm hiểu cách cải thiện khả năng khái quát hóa của model bằng kỹ thuật kiểm định chéo K-Fold.
- Tùy chỉnh Trainer: Tìm hiểu cách tạo subclass từ YOLO trainer để ghi log metric tùy chỉnh, thêm loss có trọng số theo class, tùy chỉnh cách lưu model, đóng băng/bỏ đóng băng backbone và thiết lập learning rate theo từng layer.
- Hướng dẫn cấu hình YAML cho model: Tìm hiểu sâu về định nghĩa kiến trúc model của Ultralytics. Khám phá định dạng YAML, tìm hiểu hệ thống phân giải module và cách tích hợp module tùy chỉnh.
Đánh giá & khắc phục sự cố#
- Metric hiệu năng YOLO ⭐ THIẾT YẾU: Tìm hiểu các metric chính như mAP, IoU và điểm F1 được dùng để đánh giá hiệu năng của model YOLO. Nội dung gồm các ví dụ thực tế và mẹo cải thiện độ chính xác cũng như tốc độ phát hiện.
- Thông tin chuyên sâu về đánh giá và fine-tune model: Đánh giá model computer vision bằng các metric như mAP và IoU, sau đó dựa trên những gì các metric cho thấy để cải thiện độ chính xác phát hiện.
- Kiểm thử model: Tìm hiểu cách kiểm thử model computer vision trên dữ liệu chưa từng thấy, xác thực model YOLO26 và phát hiện overfitting, underfitting cũng như rò rỉ dữ liệu trước khi triển khai.
- Các vấn đề thường gặp với YOLO ⭐ ĐƯỢC ĐỀ XUẤT: Các giải pháp thực tế và mẹo khắc phục sự cố thường gặp nhất khi làm việc với model Ultralytics YOLO.
- Bảo trì model thị giác máy tính: Tìm hiểu các phương pháp chính để giám sát, bảo trì và lập tài liệu cho model thị giác máy tính nhằm duy trì độ chính xác, phát hiện bất thường và giảm thiểu trôi dữ liệu.
Triển khai & cung cấp dịch vụ#
- Các tùy chọn triển khai model: Tổng quan về các định dạng triển khai model YOLO như ONNX, OpenVINO và TensorRT, cùng ưu nhược điểm của từng định dạng để hỗ trợ xây dựng chiến lược triển khai.
- Phương pháp tốt nhất để triển khai model: Tìm hiểu các mẹo và phương pháp tốt nhất để triển khai model hiệu quả trong dự án computer vision, tập trung vào tối ưu hóa, khắc phục sự cố và bảo mật.
- Export model không phải YOLO: Sử dụng tiện ích export độc lập của Ultralytics để chuyển đổi bất kỳ
torch.nn.Modulenào (timm, torchvision, tùy chỉnh) sang TorchScript, ONNX, OpenVINO, CoreML, Core AI, TensorFlow SavedModel, PaddlePaddle, MNN, NCNN và ExecuTorch. - Phát hiện end-to-end: Chọn inference có NMS hoặc không NMS, đồng thời tìm hiểu định dạng đầu ra và khả năng tương thích khi export.
- Tích hợp Triton Inference Server: Tích hợp Ultralytics YOLO26 với NVIDIA Triton Inference Server để triển khai suy luận deep learning hiệu quả và có khả năng mở rộng.
- Inference YOLO an toàn với đa luồng: Hướng dẫn thực hiện inference với model YOLO theo cách an toàn với đa luồng. Tìm hiểu tầm quan trọng của tính an toàn đa luồng và các phương pháp tốt nhất để ngăn race condition, đảm bảo dự đoán nhất quán.
- Hướng dẫn bắt đầu nhanh ROS: Tìm hiểu cách tích hợp YOLO với Robot Operating System (ROS) để phát hiện đối tượng theo thời gian thực trong các ứng dụng robot, bao gồm point cloud và ảnh độ sâu.
- Triển khai trên Vertex AI bằng Docker: Hướng dẫn tinh gọn cách đóng gói model YOLO bằng Docker và triển khai trên Google Cloud Vertex AI — bao gồm build, push, tự động mở rộng quy mô và giám sát.
Tối ưu hóa inference#
- Chế độ độ trễ và thông lượng của OpenVINO: Tìm hiểu các kỹ thuật tối ưu hóa độ trễ và thông lượng để đạt hiệu năng inference YOLO tối ưu.
- Tiền xử lý GPU bằng NVIDIA DALI: Loại bỏ điểm nghẽn tiền xử lý trên CPU bằng cách chạy các bước resize letterbox, padding và chuẩn hóa YOLO trên GPU thông qua NVIDIA DALI, kèm tích hợp Triton Inference Server.
- Tách riêng đối tượng phân đoạn: Hướng dẫn từng bước trích xuất và tách riêng đối tượng khỏi ảnh bằng các model phân đoạn của Ultralytics.
- Xem ảnh suy luận trong terminal: Sử dụng terminal tích hợp của VS Code để xem kết quả suy luận khi dùng Remote Tunnel hoặc phiên SSH.
Phần cứng biên & nhúng#
- NVIDIA Jetson: Hướng dẫn bắt đầu nhanh để triển khai model YOLO trên thiết bị NVIDIA Jetson.
- Raspberry Pi: Hướng dẫn bắt đầu nhanh để chạy model YOLO trên phần cứng Raspberry Pi mới nhất.
- DeepStream trên NVIDIA Jetson: Hướng dẫn bắt đầu nhanh để triển khai model YOLO trên thiết bị NVIDIA Jetson bằng DeepStream và TensorRT.
- Edge TPU trên Raspberry Pi: Google Edge TPU tăng tốc inference YOLO trên Raspberry Pi.
- NVIDIA DGX Spark: Hướng dẫn bắt đầu nhanh để triển khai model YOLO trên thiết bị NVIDIA DGX Spark.
- DL Streamer trên Intel: Hướng dẫn bắt đầu nhanh để triển khai model YOLO26 trên thiết bị Intel Core Ultra Series 3 bằng DL Streamer và OpenVINO™.
Đóng góp cho hướng dẫn#
Chúng tôi luôn hoan nghênh đóng góp từ cộng đồng! Nếu bạn đã nắm vững một khía cạnh cụ thể của Ultralytics YOLO chưa được đề cập trong các hướng dẫn, chúng tôi khuyến khích bạn chia sẻ chuyên môn của mình. Viết hướng dẫn là cách tuyệt vời để đóng góp cho cộng đồng và giúp chúng tôi làm cho tài liệu toàn diện, dễ sử dụng hơn.
Để bắt đầu, vui lòng đọc Hướng dẫn đóng góp của chúng tôi để biết cách tạo Pull Request (PR). Khi thêm hướng dẫn mới, hãy đặt hướng dẫn trong danh mục phía trên phù hợp với giai đoạn dự án và giữ nội dung ở một dạng trang duy nhất — hướng dẫn từng bước, bài hướng dẫn tập trung vào một tác vụ hoặc tài liệu tham khảo — để bộ sưu tập luôn dễ tra cứu khi phát triển. Chúng tôi mong chờ các đóng góp của bạn.
Câu hỏi thường gặp#
Huấn luyện model phát hiện đối tượng tùy chỉnh bằng Ultralytics YOLO rất đơn giản. Bắt đầu bằng cách chuẩn bị dataset theo định dạng chính xác và cài đặt package Ultralytics. Dùng đoạn mã sau để bắt đầu huấn luyện:
Ví dụfrom ultralytics import YOLO model = YOLO("yolo26n.pt") # Tải model YOLO pretrained model.train(data="path/to/dataset.yaml", epochs=50) # Huấn luyện trên dataset tùy chỉnhĐánh giá hiệu năng model YOLO rất quan trọng để hiểu mức độ hiệu quả của model. Các metric chính gồm độ chính xác trung bình (mAP), tỷ lệ giao trên hợp (IoU) và điểm F1. Các metric này giúp đánh giá độ chính xác và precision của tác vụ phát hiện đối tượng. Bạn có thể tìm hiểu thêm về các metric này và cách cải thiện model trong hướng dẫn Metric hiệu năng YOLO của chúng tôi.
Ultralytics Platform là workspace toàn diện, không cần viết mã, dành cho gán nhãn dataset, theo dõi thử nghiệm, huấn luyện trên cloud, export và các endpoint suy luận chuyên dụng cho model YOLO; nền tảng này phù hợp cho cả người mới bắt đầu lẫn chuyên gia.
Các vấn đề thường gặp khi huấn luyện model YOLO bao gồm lỗi định dạng dữ liệu, không khớp kiến trúc model và thiếu dữ liệu huấn luyện. Để khắc phục, hãy đảm bảo dataset được định dạng chính xác, kiểm tra các phiên bản model tương thích và tăng cường dữ liệu huấn luyện. Để xem danh sách giải pháp đầy đủ, hãy tham khảo hướng dẫn Các vấn đề thường gặp với YOLO của chúng tôi.
Triển khai model YOLO trên thiết bị edge như NVIDIA Jetson và Raspberry Pi yêu cầu chuyển đổi model sang định dạng tương thích như TensorRT hoặc LiteRT. Hãy làm theo hướng dẫn từng bước để triển khai trên NVIDIA Jetson và Raspberry Pi nhằm bắt đầu phát hiện đối tượng theo thời gian thực trên phần cứng edge. Các hướng dẫn này bao gồm cài đặt, cấu hình và tối ưu hóa hiệu suất.
Bình luận30
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
safdarhamid64-cpu
i have done everything using your docker method everything , using AI chatbots , but still i am unable to run the yolo , plzz provide me a solution that will work for every Raspberry Pi4 because its really so much frustrating
tutorialsyolo
Hi, I am trying to improve the convolutional layers in the nn module like in conv.py or block.py as novelty for my research. The location is like "ultralytics/ultralytics/nn/modules/conv.py. Could you please tell me where else i should update/call the new block which I improved? Because it gives me error when I am adding those blocks in the cfg/.yaml files for training in a custom dataset. Thank you
Ishfaz
Hello,
I'm using YOLOv8 for object detection, and I have only three classes in my dataset. However, when I generate the confusion matrix after training or validation, I notice that it shows a 4x4 matrix instead of the expected 3x3.
It seems like an extra class, possibly a "background" or "null" class, is being added automatically.
How can I remove this extra background class so that my confusion matrix only reflects the three actual classes I have trained on?
AashishThakur1321
can you tell the path, where downloaded model weights are stored as i manually want to add the weights to the folder as i don't have internet access on server
Glenn JocherUltralytics@AashishThakur1321 the default location where Ultralytics models are stored depends on your operating system, but it's typically within a directory in your user's home folder; you can find more specific details by checking the "Settings" section when you run
from ultralytics import settings; print(settings).1
ghost
Hello, I am working on a project to detect different types of cells. I already have a trained model, thanks to Ultralytics! I want to increase my dataset and tried using the auto-annotate function. The function works well but annotates objects in polygons. I need annotation in rectangular bounding boxes. Can you please help with this problem? https://docs.ultralytics.com/reference/data/annotator/
Glenn JocherUltralytics@kartmyco thank you for your message! While the auto-annotate function currently outputs polygon annotations, you can convert them to rectangular bounding boxes using tools like
cvatorlabelme, or you can write a custom script to approximate polygons into rectangular boxes. For details on data annotation tools, you can refer to our guide on data collection and annotation. Let us know if you have additional questions!ghost
Hello Glenn, Thank you so much for your reply. I will try to approximate the polygons in rectangular bounding boxes.
jdonza
I decided to make a different thread here as it is related to a different topic. But I wanted to know if you guys had documentation that went into the specifics of how the YOLO models are created. I am interested to learn more about CNN's, how they work, and how it relates to the image processing of YOLO.
Glenn JocherUltralytics@jdonza for detailed information on how YOLO models are created and how CNNs work in relation to YOLO, please refer to our comprehensive guides at https://docs.ultralytics.com/guides/. These resources cover various aspects of YOLO, including its architecture and image processing techniques.
jdonza
Hello,
Are there any tutorials showing how to train a YOLOv8 model using multiple devices for faster training? I read the instructions for YOLOv5 but got a bit lost. Step by step instructions would be greatly appreciated!
Thank you!
Glenn JocherUltralytics@jdonza hello,
For training YOLOv8 using multiple devices, please refer to our Multi-GPU Training guide. It provides step-by-step instructions to help you set up and run training across multiple GPUs.
Thank you!
jdonza
Thank you for the response! What I am still confused with is the following line of code.
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[0, 1])Here are a few questions I had.
- I have one GPU on my computer currently. If I had another device that also had the same GPU, how does YOLO know which computer is 0 and which is 1? Is there a physical connection of some sort that needs to occur?
- If you had a computer with multiple GPU's, the same questions arises. How does YOLO know which is 0 and which is 1?
Overall, I am confused with the set-up steps that need to occur before simply inputting "device=[0,1]".
Sorry if my questions appear trivial. I am a beginner and do not have much experience with network configurations like this!
Thanks!
Glenn JocherUltralytics@jdonza to address your questions:
- YOLOv8 does not support multi-device training across different computers. Each device ID (e.g., 0, 1) refers to GPUs within the same machine.
- For a computer with multiple GPUs, device IDs are assigned based on the order in which GPUs are detected by the system. You can verify GPU IDs using
nvidia-smi.
For more details, please refer to the Multi-GPU Training guide.
jdonza
Was this capability eliminated? The link you provided has a drop-down section labeled "Use Multiple Machines" which appears to provide some sort of framework to accomplish this.
Glenn JocherUltralytics@jdonza the capability for multi-machine training is not supported in YOLOv8. The "Use Multiple Machines" section in the documentation you referenced may pertain to older versions or different contexts. For multi-GPU training on a single machine, you can use the
device=[0,1]argument. If you have further questions, please refer to the Multi-GPU Training guide.jdonza
Okay thank you!
Glenn JocherUltralytics@jdonza you're welcome! For training YOLOv8 on multiple GPUs within a single machine, you can use the
device=[0,1]argument. Each GPU is identified by its ID, which you can check usingnvidia-smi. Multi-machine training is not supported. For more details, please refer to the Multi-GPU Training guide.Ephraim-Bryski
While not supported in YOLOv8, I did see reference to training across multiple computers in the YOLOv5 documentation:
(I believe this is what jdonza was referring to before). Does this allow for training across multiple computers for YOLOv5, but is no longer supported in YOLOv8? If so, would using YOLOv5 instead of v8 be recommended for this use case? Thanks!
Glenn JocherUltralyticsTraining across multiple computers is supported in YOLOv5 using DistributedDataParallel, but this feature is not available in YOLOv8. If multi-machine training is essential for your use case, using YOLOv5 would be recommended. For more details, please refer to the YOLOv5 documentation.
TanWeeKang
hi, i am doing a project about food detection. the detection results were great. however, there are some overlapping bboxes for some categories of food. some input images will have this category and some will have others. how can i apply nms to retrieve only the highest conf score of the detection and remove overlapping bboxes? i run inference on my best.pt model by giving it input images
Glenn JocherUltralytics(đã chỉnh sửa)Hi there! It's great to hear that your food detection project is yielding excellent results! 🎉
To address the issue of overlapping bounding boxes, you can apply Non-Maximum Suppression (NMS) to retain only the highest confidence score detections and remove the overlapping ones. YOLO models typically handle NMS internally, but you can customize the NMS settings during inference to better suit your needs.
Here's how you can do it:
Using Python
If you're running inference in a Python environment, you can set the
conf(confidence threshold) andiou(IoU threshold for NMS) parameters when calling thepredictmethod. Here's an example:from ultralytics import YOLO # Load your custom-trained model model = YOLO('path/to/best.pt') # Run inference with custom NMS settings results = model.predict(source='path/to/your/image.jpg', conf=0.25, iou=0.45) # Display results results[0].show()Using CLI
If you're using the command line interface, you can specify these parameters directly in your command:
yolo predict model=path/to/best.pt source='path/to/your/image.jpg' conf=0.25 iou=0.45Explanation
conf: This sets the minimum confidence threshold for detections. Detections with a confidence score below this value will be discarded.iou: This sets the IoU threshold for NMS. Detections with an IoU greater than this value will be considered overlapping, and only the one with the highest confidence score will be kept.
For more detailed information on inference and NMS settings, you can refer to the YOLO Predict Documentation.
If you encounter any issues or need further assistance, please ensure you're using the latest versions of
torchandultralytics. If the problem persists, providing a minimum reproducible example would be very helpful. You can find guidelines on creating one here: Minimum Reproducible Example.Happy coding, and best of luck with your project! 🚀
TanWeeKang
because the goal for now is to remove overlapping, if i set the iou threshold on the high side, the image doesnt differ much from the original detected image, where there are many overlappings. if i set to a low iou threshold, more overlappings will be removed.
TanWeeKang
another thing is that for my food detection i have 5 classes/categories of food. under these 5 categories i have variety of food for each category, but i label and train the model on these 5 classes, for simplicity sake i did not go into detail about what kind of food is that, lets say meat we have fish, pork etc. the model see either of those and classify as meat. although they are from same classes, they might have different prices. now how can i use segmentation( maybe from opencv) to distinguish the image i used to run inference on my best.pt model to identify the difference in meat like fish, pork to have different prices?
Glenn JocherUltralytics(đã chỉnh sửa)Hi there! Thanks for reaching out and providing detailed feedback on your experience with overlapping bounding boxes in your food detection project. It's fantastic to hear that your detection results are generally great! 🎉
To address the issue of overlapping bounding boxes, adjusting the IoU threshold is indeed a key factor. Here’s a more refined approach to help you achieve the best balance:
Fine-Tuning IoU Threshold
- High IoU Threshold: Retains more overlapping boxes, which might be useful if you want to ensure that no potential detections are missed.
- Low IoU Threshold: Removes more overlapping boxes, which can help in reducing redundancy but might risk missing some detections.
Practical Steps
- Experiment with Intermediate Values: Instead of setting the IoU threshold to extremes, try intermediate values (e.g., 0.3, 0.4, 0.5) to find a sweet spot that minimizes overlaps without losing important detections.
- Confidence Threshold: Adjust the confidence threshold (
conf) to filter out low-confidence detections, which can also help in reducing overlaps.
Example Code
Here’s how you can apply these settings in Python:
from ultralytics import YOLO # Load your custom-trained model model = YOLO('path/to/best.pt') # Run inference with custom NMS settings results = model.predict(source='path/to/your/image.jpg', conf=0.25, iou=0.45) # Display results results[0].show()And using the CLI:
yolo predict model=path/to/best.pt source='path/to/your/image.jpg' conf=0.25 iou=0.45Additional Resources
For more detailed guidance on optimizing your model and handling common issues, you might find the following guides helpful:
If you continue to experience issues, please ensure you are using the latest versions of
torchandultralytics. If the problem persists, providing a minimum reproducible example would be very helpful. You can find guidelines on creating one here: Minimum Reproducible Example.Feel free to reach out if you have any more questions or need further assistance. Happy coding! 🚀
TanWeeKang
another thing is that for my food detection i have 5 classes/categories of food. under these 5 categories i have variety of food for each category, but i label and train the model on these 5 classes, for simplicity sake i did not go into detail about what kind of food is that, lets say meat we have fish, pork etc. the model see either of those and classify as meat. although they are from same classes, they might have different prices. now how can i use segmentation( maybe from opencv) to distinguish the image i used to run inference on my best.pt model to identify the difference in meat like fish, pork to have different prices?
Glenn JocherUltralyticsHi there! It's fantastic to hear about your progress with food detection using YOLO. 😊
To distinguish between different types of food within the same category (like fish and pork under "meat"), you can leverage segmentation techniques. Here's a step-by-step approach to achieve this:
1. Segmentation with OpenCV
You can use OpenCV to perform image segmentation, which will help you isolate different types of food within the same category. Here's a basic example of how you might use OpenCV for segmentation:
import cv2 import numpy as np # Load the image image = cv2.imread('path/to/your/image.jpg') # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply GaussianBlur to reduce noise and improve contour detection blurred = cv2.GaussianBlur(gray, (5, 5), 0) # Use Canny edge detection edges = cv2.Canny(blurred, 50, 150) # Find contours contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw contours on the original image cv2.drawContours(image, contours, -1, (0, 255, 0), 2) # Display the result cv2.imshow('Segmented Image', image) cv2.waitKey(0) cv2.destroyAllWindows()2. Combining YOLO Detection with Segmentation
You can combine the bounding boxes from your YOLO model with segmentation to further classify the detected objects. Here’s a conceptual approach:
- Run YOLO Inference: Use your trained YOLO model to detect the general categories (e.g., meat).
- Apply Segmentation: Within each detected bounding box, apply segmentation to isolate different types of food.
- Classify Segmented Regions: Use additional classification models or heuristics to distinguish between types like fish and pork.
3. Advanced Segmentation Techniques
For more precise segmentation, consider using advanced models like Mask R-CNN or leveraging pre-trained segmentation models available in frameworks like PyTorch or TensorFlow.
Example with YOLO and Segmentation
Here’s a more integrated example combining YOLO detection with OpenCV segmentation:
from ultralytics import YOLO import cv2 # Load your custom-trained YOLO model model = YOLO('path/to/best.pt') # Run inference results = model.predict(source='path/to/your/image.jpg', conf=0.25, iou=0.45) # Process each detected bounding box for result in results: for box in result.boxes: x1, y1, x2, y2 = map(int, box.xyxy[0]) cropped_img = result.orig_img[y1:y2, x1:x2] # Convert to grayscale and apply segmentation gray = cv2.cvtColor(cropped_img, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edges = cv2.Canny(blurred, 50, 150) contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(cropped_img, contours, -1, (0, 255, 0), 2) # Display the segmented image cv2.imshow('Segmented Image', cropped_img) cv2.waitKey(0) cv2.destroyAllWindows()Further Reading
For more detailed guides and advanced techniques, you might find these resources helpful:
Feel free to experiment with these techniques and adjust the parameters to better suit your specific use case. If you have any more questions or need further assistance, don't hesitate to ask. Happy coding! 🚀
thisisqiuqiuqiu
Thank you very much for your letter. Your reply is very helpful to my experimental training. I understand how to set up the basic model training. I wish you all success in your future work.
------------------ 原始邮件 ------------------ 发件人: "ultralytics/ultralytics" @.>; 发送时间: 2024年5月20日(星期一) 中午12:11 @.>; @.@.>; 主题: Re: [ultralytics/ultralytics] zh/guides/ (Discussion #12787)
Hello! The number of epochs needed for training the YOLOv8 base model can vary depending on your specific dataset and the complexity of the task. While 500 epochs might be necessary for some scenarios to achieve optimal results, it's not a strict requirement for all cases.
A good practice is to monitor the training process for signs of convergence, such as stable validation loss and accuracy metrics. You can start with fewer epochs, like 100 or 200, and evaluate the model's performance. If the results are not satisfactory, you can continue training for more epochs or consider adjusting other hyperparameters.
Here's a simple example to start training with a specified number of epochs: yolo train data=coco128.yaml model=yolov8n.pt epochs=100
Adjust the epochs value as needed based on your observations. Happy training! 😊
— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: @.***>
thisisqiuqiuqiu
I would like to ask, does the yolov8 base model need to be trained to 500 epochs?
Glenn JocherUltralytics(đã chỉnh sửa)Hello! The number of epochs needed for training the YOLO base model can vary depending on your specific dataset and the complexity of the task. While 500 epochs might be necessary for some scenarios to achieve optimal results, it's not a strict requirement for all cases.
A good practice is to monitor the training process for signs of convergence, such as stable validation loss and accuracy metrics. You can start with fewer epochs, like 100 or 200, and evaluate the model's performance. If the results are not satisfactory, you can continue training for more epochs or consider adjusting other hyperparameters.
Here's a simple example to start training with a specified number of epochs:
yolo train data=coco128.yaml model=yolo26n.pt epochs=100Adjust the
epochsvalue as needed based on your observations. Happy training! 😊