콘텐츠로 건너뛰기

Python 사용법

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



참고: 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")

Train

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

Train

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 켜짐 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 metrics (객체 감지 및 분할용) 또는 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)

사용자 정의 작업을 지원하거나 연구 개발 아이디어를 탐색하도록 Trainer를 쉽게 사용자 정의할 수 있습니다. Ultralytics YOLO의 모듈식 설계를 통해 새로운 컴퓨터 비전 작업을 수행하든 기존 모델을 미세 조정하여 성능을 향상시키든 특정 요구 사항에 맞게 프레임워크를 조정할 수 있습니다.

사용자 정의 튜토리얼

FAQ

객체 탐지를 위해 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()

Predict 모드 섹션에서 더 자세한 예제를 참조하세요.

YOLO에서 사용할 수 있는 다양한 모드는 무엇입니까?

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

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

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

내 데이터 세트를 사용하여 사용자 정의 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)

훈련에 대한 자세한 내용과 사용 예제에 대한 하이퍼링크는 Train Mode 페이지를 참조하십시오.

배포를 위해 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")

다양한 내보내기 옵션은 Export Mode 문서를 참조하십시오.

다른 데이터 세트에서 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 Mode 페이지를 확인하십시오.



📅 1년 전에 생성됨 ✏️ 5개월 전에 업데이트됨

댓글