콘텐츠로 건너뛰기

Python 사용법

Welcome to the YOLO11 Python Usage documentation! This guide is designed to help you seamlessly integrate YOLO11 into your Python projects for object detection, segmentation, and classification. Here, you'll learn how to load and use pretrained models, train new models, and perform predictions on images. The easy-to-use Python interface is a valuable resource for anyone looking to incorporate YOLO11 into their Python projects, allowing you to quickly implement advanced object detection capabilities. Let's get started!



Watch: Mastering Ultralytics YOLO11: Python

예를 들어, 사용자는 몇 줄의 코드만으로 모델을 로드하고, 학습하고, 유효성 검사 세트에서 성능을 평가하고, ONNX 형식으로 내보낼 수도 있습니다.

Python

from ultralytics import YOLO

# Create a new YOLO model from scratch
model = YOLO("yolo11n.yaml")

# Load a pretrained YOLO model (recommended for training)
model = YOLO("yolo11n.pt")

# Train the model using the 'coco8.yaml' dataset for 3 epochs
results = model.train(data="coco8.yaml", epochs=3)

# Evaluate the model's performance on the validation set
results = model.val()

# Perform object detection on an image using the model
results = model("https://ultralytics.com/images/bus.jpg")

# Export the model to ONNX format
success = model.export(format="onnx")

기차

Train mode is used for training a YOLO11 model on a custom dataset. In this mode, the model is trained using the specified dataset and hyperparameters. The training process involves optimizing the model's parameters so that it can accurately predict the classes and locations of objects in an image.

기차

from ultralytics import YOLO

model = YOLO("yolo11n.pt")  # pass any model type
results = model.train(epochs=5)
from ultralytics import YOLO

model = YOLO("yolo11n.yaml")
results = model.train(data="coco8.yaml", epochs=5)
model = YOLO("last.pt")
results = model.train(resume=True)

열차 예시

Val

Val mode is used for validating a YOLO11 model after it has been trained. In this mode, the model is evaluated on a validation set to measure its accuracy and generalization performance. This mode can be used to tune the hyperparameters of the model to improve its performance.

Val

from ultralytics import YOLO

# Load a YOLO11 model
model = YOLO("yolo11n.yaml")

# Train the model
model.train(data="coco8.yaml", epochs=5)

# Validate on training data
model.val()
from ultralytics import YOLO

# Load a YOLO11 model
model = YOLO("yolo11n.yaml")

# Train the model
model.train(data="coco8.yaml", epochs=5)

# Validate on separate data
model.val(data="path/to/separate/data.yaml")

Val 예제

예측

Predict mode is used for making predictions using a trained YOLO11 model on new images or videos. In this mode, the model is loaded from a checkpoint file, and the user can provide images or videos to perform inference. The model predicts the classes and locations of objects in the input images or videos.

예측

import cv2
from PIL import Image

from ultralytics import YOLO

model = YOLO("model.pt")
# accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam
results = model.predict(source="0")
results = model.predict(source="folder", show=True)  # Display preds. Accepts all YOLO predict arguments

# from PIL
im1 = Image.open("bus.jpg")
results = model.predict(source=im1, save=True)  # save plotted images

# from ndarray
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True)  # save predictions as labels

# from list of PIL/ndarray
results = model.predict(source=[im1, im2])
# results would be a list of Results object including all the predictions by default
# but be careful as it could occupy a lot memory when there're many images,
# especially the task is segmentation.
# 1. return as a list
results = model.predict(source="folder")

# results would be a generator which is more friendly to memory by setting stream=True
# 2. return as a generator
results = model.predict(source=0, stream=True)

for result in results:
    # Detection
    result.boxes.xyxy  # box with xyxy format, (N, 4)
    result.boxes.xywh  # box with xywh format, (N, 4)
    result.boxes.xyxyn  # box with xyxy format but normalized, (N, 4)
    result.boxes.xywhn  # box with xywh format but normalized, (N, 4)
    result.boxes.conf  # confidence score, (N, 1)
    result.boxes.cls  # cls, (N, 1)

    # Segmentation
    result.masks.data  # masks, (N, H, W)
    result.masks.xy  # x,y segments (pixels), List[segment] * N
    result.masks.xyn  # x,y segments (normalized), List[segment] * N

    # Classification
    result.probs  # cls prob, (num_class, )

# Each result is composed of torch.Tensor by default,
# in which you can easily use following functionality:
result = result.cuda()
result = result.cpu()
result = result.to("cpu")
result = result.numpy()

예측 예제

내보내기

Export mode is used for exporting a YOLO11 model to a format that can be used for deployment. In this mode, the model is converted to a format that can be used by other software applications or hardware devices. This mode is useful when deploying the model to production environments.

내보내기

Export an official YOLO11n model to ONNX with dynamic batch-size and image-size.

from ultralytics import YOLO

model = YOLO("yolo11n.pt")
model.export(format="onnx", dynamic=True)

Export an official YOLO11n model to TensorRT on device=0 CUDA 장치에서 가속을 위해.

from ultralytics import YOLO

model = YOLO("yolo11n.pt")
model.export(format="onnx", device=0)

내보내기 예제

트랙

Track mode is used for tracking objects in real-time using a YOLO11 model. In this mode, the model is loaded from a checkpoint file, and the user can provide a live video stream to perform real-time object tracking. This mode is useful for applications such as surveillance systems or self-driving cars.

트랙

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n.pt")  # load an official detection model
model = YOLO("yolo11n-seg.pt")  # load an official segmentation model
model = YOLO("path/to/best.pt")  # load a custom model

# Track with the model
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")

트랙 예시

벤치마크

Benchmark mode is used to profile the speed and accuracy of various export formats for YOLO11. The benchmarks provide information on the size of the exported format, its mAP50-95 메트릭(객체 감지 및 세분화용) 또는 accuracy_top5 메트릭(분류용)과 ONNX, OpenVINO, TensorRT 등과 같은 다양한 내보내기 형식에서 이미지당 밀리초 단위의 추론 시간을 확인할 수 있습니다. 이 정보는 사용자가 속도와 정확성에 대한 요구 사항에 따라 특정 사용 사례에 맞는 최적의 내보내기 형식을 선택하는 데 도움이 될 수 있습니다.

벤치마크

Benchmark an official YOLO11n model across all export formats.

from ultralytics.utils.benchmarks import benchmark

# Benchmark
benchmark(model="yolo11n.pt", data="coco8.yaml", imgsz=640, half=False, device=0)

벤치마크 예시

트레이너 사용

YOLO 모델 클래스는 트레이너 클래스의 상위 레벨 래퍼입니다. 각 YOLO 작업에는 다음을 상속하는 자체 트레이너가 있습니다. BaseTrainer.

탐지 트레이너 예시

from ultralytics.models.yolo import DetectionPredictor, DetectionTrainer, DetectionValidator

# trainer
trainer = DetectionTrainer(overrides={})
trainer.train()
trained_model = trainer.best

# Validator
val = DetectionValidator(args=...)
val(model=trained_model)

# predictor
pred = DetectionPredictor(overrides={})
pred(source=SOURCE, model=trained_model)

# resume from last weight
overrides["resume"] = trainer.last
trainer = detect.DetectionTrainer(overrides=overrides)

트레이너를 쉽게 사용자 지정하여 맞춤형 작업을 지원하거나 R&D 아이디어를 탐색할 수 있습니다. 사용자 지정에 대해 자세히 알아보기 Trainers, Validators 그리고 Predictors 사용자 지정 섹션에서 프로젝트 요구 사항에 맞게 조정할 수 있습니다.

사용자 지정 튜토리얼

자주 묻는 질문

How can I integrate YOLO11 into my Python project for object detection?

Integrating Ultralytics YOLO11 into your Python projects is simple. You can load a pre-trained model or train a new model from scratch. Here's how to get started:

from ultralytics import YOLO

# Load a pretrained YOLO model
model = YOLO("yolo11n.pt")

# Perform object detection on an image
results = model("https://ultralytics.com/images/bus.jpg")

# Visualize the results
for result in results:
    result.show()

예측 모드 섹션에서 더 자세한 예시를 확인하세요.

What are the different modes available in YOLO11?

Ultralytics YOLO11 provides various modes to cater to different machine learning workflows. These include:

  • 기차: 사용자 지정 데이터 세트를 사용하여 모델을 학습합니다.
  • Val: 유효성 검사 세트에서 모델 성능을 검증합니다.
  • 예측: 새로운 이미지 또는 비디오 스트림을 예측합니다.
  • 내보내기: 내보내기 : ONNX, TensorRT 과 같은 다양한 형식으로 모델을 내보냅니다.
  • 트랙: 비디오 스트림에서 실시간 개체 추적.
  • 벤치마크: 다양한 구성에서 모델 성능을 벤치마크합니다.

각 모드는 모델 개발 및 배포의 다양한 단계를 위한 포괄적인 기능을 제공하도록 설계되었습니다.

How do I train a custom YOLO11 model using my dataset?

To train a custom YOLO11 model, you need to specify your dataset and other hyperparameters. Here's a quick example:

from ultralytics import YOLO

# Load the YOLO model
model = YOLO("yolo11n.yaml")

# Train the model with custom dataset
model.train(data="path/to/your/dataset.yaml", epochs=10)

교육에 대한 자세한 내용과 예제 사용법에 대한 하이퍼링크는 교육 모드 페이지를 참조하세요.

How do I export YOLO11 models for deployment?

Exporting YOLO11 models in a format suitable for deployment is straightforward with the export 함수를 사용하세요. 예를 들어 모델을 ONNX 형식으로 내보낼 수 있습니다:

from ultralytics import YOLO

# Load the YOLO model
model = YOLO("yolo11n.pt")

# Export the model to ONNX format
model.export(format="onnx")

다양한 내보내기 옵션에 대해서는 내보내기 모드 문서를 참조하세요.

Can I validate my YOLO11 model on different datasets?

Yes, validating YOLO11 models on different datasets is possible. After training, you can use the validation mode to evaluate the performance:

from ultralytics import YOLO

# Load a YOLO11 model
model = YOLO("yolo11n.yaml")

# Train the model
model.train(data="coco8.yaml", epochs=5)

# Validate the model on a different dataset
model.val(data="path/to/separate/data.yaml")

자세한 예시와 사용법은 Val 모드 페이지에서 확인하세요.

📅 Created 11 months ago ✏️ Updated 8 days ago

댓글