콘텐츠로 건너뛰기

Python 사용법

Ultralytics YOLO Python 사용 설명서에 오신 것을 환영합니다! 이 가이드는 객체 감지, 세분화분류를 위해 Ultralytics YOLO Python 프로젝트에 원활하게 통합하는 데 도움을 주기 위해 작성되었습니다. 여기에서는 사전 학습된 모델을 로드 및 사용하고, 새 모델을 학습시키고, 이미지에 대한 예측을 수행하는 방법을 배웁니다. 사용하기 쉬운 Python 인터페이스는 고급 객체 감지 기능을 빠르게 구현할 수 있도록 Python 프로젝트에 YOLO 통합하려는 모든 사람에게 유용한 리소스입니다. 지금 바로 시작해보세요!



Watch: Ultralytics YOLO 마스터하기: 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")

기차

훈련 모드는 사용자 지정 데이터 세트에서 YOLO 모델을 훈련하는 데 사용됩니다. 이 모드에서는 지정된 데이터 세트와 하이퍼파라미터를 사용하여 모델을 학습시킵니다. 훈련 과정에는 이미지에서 객체의 클래스와 위치를 정확하게 예측할 수 있도록 모델의 매개변수를 최적화하는 작업이 포함됩니다.

기차

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 모드는 학습이 완료된 YOLO 모델을 검증하는 데 사용됩니다. 이 모드에서는 유효성 검사 세트에서 모델을 평가하여 정확도와 일반화 성능을 측정합니다. 이 모드는 모델의 하이퍼파라미터를 조정하여 성능을 개선하는 데 사용할 수 있습니다.

Val

from ultralytics import YOLO

# Load a YOLO 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 YOLO 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 예제

예측

예측 모드는 새로운 이미지 또는 동영상에 대해 학습된 YOLO 모델을 사용하여 예측하는 데 사용됩니다. 이 모드에서는 체크포인트 파일에서 모델이 로드되며, 사용자는 추론을 수행할 이미지 또는 동영상을 제공할 수 있습니다. 모델은 입력된 이미지 또는 동영상에서 객체의 클래스 및 위치를 예측합니다.

예측

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()

예측 예제

내보내기

내보내기 모드는 YOLO 모델을 배포에 사용할 수 있는 형식으로 내보내는 데 사용됩니다. 이 모드에서는 모델이 다른 소프트웨어 애플리케이션이나 하드웨어 장치에서 사용할 수 있는 형식으로 변환됩니다. 이 모드는 모델을 프로덕션 환경에 배포할 때 유용합니다.

내보내기

공식 YOLO 모델을 다음 주소로 내보내기 ONNX 동적 배치 크기와 이미지 크기로 내보냅니다.

from ultralytics import YOLO

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

공식 YOLO 모델을 다음 주소로 내보내기 TensorRT on device=0 CUDA 장치에서 가속을 위해.

from ultralytics import YOLO

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

내보내기 예제

트랙

추적 모드는 YOLO 모델을 사용하여 실시간으로 객체를 추적하는 데 사용됩니다. 이 모드에서는 체크포인트 파일에서 모델을 로드하고 사용자가 실시간 비디오 스트림을 제공하여 실시간 객체 추적을 수행할 수 있습니다. 이 모드는 감시 시스템이나 자율 주행 차량과 같은 애플리케이션에 유용합니다.

트랙

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")

트랙 예시

벤치마크

벤치마크 모드 YOLO 다양한 내보내기 형식의 속도와 정확도를 프로파일링하는 데 사용됩니다. 이 벤치마크는 내보낸 형식의 크기, 내보낸 형식의 mAP50-95 메트릭(객체 감지 및 세분화용) 또는 accuracy_top5 메트릭(분류용)과 ONNX 같은 다양한 내보내기 형식에서 이미지당 밀리초 단위로 추론 시간을 측정할 수 있습니다, OpenVINO, TensorRT 등을 지원합니다. 이 정보는 사용자가 속도와 정확성에 대한 요구 사항에 따라 특정 사용 사례에 맞는 최적의 내보내기 형식을 선택하는 데 도움이 될 수 있습니다.

벤치마크

모든 내보내기 형식에서 공식 YOLO 모델을 벤치마킹하세요.

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 = DetectionTrainer(overrides=overrides)

트레이너를 쉽게 사용자 지정하여 맞춤형 작업을 지원하거나 연구 및 개발 아이디어를 탐색할 수 있습니다. 새로운 컴퓨터 비전 작업을 수행하거나 더 나은 성능을 위해 기존 모델을 미세 조정하는 등, Ultralytics YOLO 모듈식 설계를 통해 특정 요구 사항에 맞게 프레임워크를 조정할 수 있습니다.

사용자 지정 튜토리얼

자주 묻는 질문

객체 감지를 위해 YOLO Python 프로젝트에 통합하려면 어떻게 해야 하나요?

Ultralytics YOLO Python 프로젝트에 통합하는 것은 간단합니다. 미리 학습된 모델을 로드하거나 처음부터 새 모델을 학습할 수 있습니다. 시작하는 방법은 다음과 같습니다:

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()

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

YOLO 사용할 수 있는 다양한 모드에는 어떤 것이 있나요?

Ultralytics YOLO 다양한 머신 러닝 워크플로우에 맞는 다양한 모드를 제공합니다. 여기에는 다음이 포함됩니다:

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

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

내 데이터 집합을 사용하여 사용자 지정 YOLO 모델을 훈련하려면 어떻게 해야 하나요?

사용자 지정 YOLO 모델을 학습하려면 데이터 세트와 기타 하이퍼파라미터를 지정해야 합니다. 다음은 간단한 예입니다:

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)

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

배포를 위해 YOLO 모델을 내보내려면 어떻게 해야 하나요?

배포에 적합한 형식으로 YOLO 모델을 내보내는 방법은 다음과 같이 간단합니다. export 함수를 사용하세요. 예를 들어 모델을 ONNX 형식으로 내보낼 수 있습니다:

from ultralytics import YOLO

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

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

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

다른 데이터 세트에서 YOLO 모델을 검증할 수 있나요?

예, 다양한 데이터 세트에서 YOLO 모델을 검증할 수 있습니다. 학습 후 유효성 검사 모드를 사용하여 성능을 평가할 수 있습니다:

from ultralytics import YOLO

# Load a YOLO 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 모드 페이지에서 확인하세요.

📅1 년 전 생성됨 ✏️ 업데이트됨 8 일 전

댓글