Python 사용법#
Ultralytics YOLO Python 사용법 문서에 오신 것을 환영합니다! 이 가이드는 객체 검출, 인스턴스 분할, 시맨틱 분할, 깊이 추정, 분류를 위해 Ultralytics YOLO를 Python 프로젝트에 원활하게 통합할 수 있도록 설계되었습니다. 여기서는 사전 학습된 모델을 로드 및 사용하는 방법, 새 모델을 학습하는 방법, 이미지에 대해 예측을 수행하는 방법을 배울 수 있습니다. 사용하기 쉬운 Python 인터페이스는 YOLO를 Python 프로젝트에 통합하려는 모든 사용자에게 유용한 리소스이며, 고급 객체 검출 기능을 빠르게 구현할 수 있게 해줍니다. 시작해 봅시다!
Watch: Mastering Ultralytics YOLO: Python
예를 들어, 사용자는 몇 줄의 코드만으로 모델을 로드하고, 학습하고, 검증 세트에서 성능을 평가하고, ONNX 형식으로 내보내기까지 수행할 수 있습니다.
from ultralytics import YOLO
# Create a new YOLO model from scratch
model = YOLO("yolo26n.yaml")
# Load a pretrained YOLO model (recommended for training)
model = YOLO("yolo26n.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("yolo26n.pt") # pass any model type
results = model.train(epochs=5)검증#
검증 모드는 YOLO 모델이 학습된 후에 모델을 검증하는 데 사용됩니다. 이 모드에서는 모델이 검증 세트에서 평가되어 정확도와 일반화 성능을 측정합니다. 이 모드를 사용하여 모델의 하이퍼파라미터를 튜닝하여 성능을 향상시킬 수 있습니다.
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo26n.yaml")
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate on training data
model.val()Prediction#
예측 모드는 학습된 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])내보내기#
내보내기 모드는 배포에 사용할 수 있는 형식으로 YOLO 모델을 내보내는 데 사용됩니다. 이 모드에서는 다른 소프트웨어 애플리케이션이나 하드웨어 장치에서 사용할 수 있는 형식으로 모델이 변환됩니다. 이 모드는 모델을 프로덕션 환경에 배포할 때 유용합니다.
동적 배치 크기 및 이미지 크기로 공식 YOLO 모델을 ONNX로 내보냅니다.
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.export(format="onnx", dynamic=True)추적#
추적 모드는 YOLO 모델을 사용하여 실시간으로 객체를 추적하는 데 사용됩니다. 이 모드에서는 체크포인트 파일에서 모델이 로드되며, 사용자는 라이브 비디오 스트림을 제공하여 실시간 객체 추적을 수행할 수 있습니다. 이 모드는 감시 시스템이나 자율주행차와 같은 애플리케이션에 유용합니다.
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.pt") # load an official detection model
model = YOLO("yolo26n-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_top1 메트릭, 그리고 ONNX, OpenVINO, TensorRT 등을 비롯한 다양한 내보내기 형식에 걸쳐 이미지당 밀리초 단위의 추론 시간을 제공합니다. 이 정보는 사용자가 속도와 정확도 요구사항에 따라 특정 유스케이스에 최적의 내보내기 형식을 선택하는 데 도움을 줍니다.
모든 내보내기 형식에 걸쳐 공식 YOLO 모델을 벤치마킹합니다.
from ultralytics.utils.benchmarks import benchmark
# Benchmark
benchmark(model="yolo26n.pt", data="coco8.yaml", imgsz=640, device=0)트레이너 사용#
YOLO 모델 클래스는 Trainer 클래스의 고수준 래퍼 역할을 합니다. 각 YOLO 태스크에는 BaseTrainer을 상속하는 고유한 트레이너가 있습니다. 이 아키텍처는 머신러닝 워크플로에서 더 큰 유연성과 커스터마이징을 허용합니다.
from ultralytics.models.yolo.detect import DetectionPredictor, DetectionTrainer, DetectionValidator
overrides = {"model": "yolo26n.pt", "data": "coco8.yaml", "epochs": 3}
# Trainer
trainer = DetectionTrainer(overrides=overrides)
trainer.train()
trained_model = trainer.best # path to best.pt
# Validator
validator = DetectionValidator(args={"data": "coco8.yaml"})
validator(model=trained_model)
# Predictor
predictor = DetectionPredictor(overrides={"model": trained_model})
predictor(source="https://ultralytics.com/images/bus.jpg")
# Resume from the last checkpoint
trainer = DetectionTrainer(overrides={**overrides, "resume": trainer.last})트레이너를 쉽게 커스터마이징하여 커스텀 태스크를 지원하거나 연구 개발 아이디어를 탐색할 수 있습니다. Ultralytics YOLO의 모듈식 설계 덕분에 새로운 컴퓨터 비전 태스크를 작업하거나 더 나은 성능을 위해 기존 모델을 미세 조정할 때 프레임워크를 특정 요구에 맞게 조정할 수 있습니다.
FAQ#
Ultralytics YOLO를 Python 프로젝트에 통합하는 것은 간단합니다. 사전 학습된 모델을 로드하거나 처음부터 새 모델을 학습할 수 있습니다. 시작하는 방법은 다음과 같습니다:
from ultralytics import YOLO # Load a pretrained YOLO model model = YOLO("yolo26n.pt") # Perform object detection on an image results = model("https://ultralytics.com/images/bus.jpg") # Visualize the results for result in results: result.show()더 자세한 예제는 예측 모드 섹션에서 확인하세요.
Ultralytics YOLO는 다양한 머신러닝 워크플로에 맞추기 위해 다양한 모드를 제공합니다. 여기에는 다음이 포함됩니다:
- 학습: 커스텀 데이터셋을 사용하여 모델을 학습합니다.
- 검증: 검증 세트에서 모델 성능을 검증합니다.
- 예측: 새로운 이미지나 비디오 스트림에 대해 예측을 수행합니다.
- 내보내기: ONNX 및 TensorRT 같은 다양한 형식으로 모델을 내보냅니다.
- 추적: 비디오 스트림에서 실시간 객체 추적을 수행합니다.
- 벤치마크: 다양한 구성에 걸쳐 모델 성능을 벤치마킹합니다.
각 모드는 모델 개발 및 배포의 다양한 단계를 위한 포괄적인 기능을 제공하도록 설계되었습니다.
배포에 적합한 형식으로 YOLO 모델을 내보내는 것은
export함수를 사용하면 간단합니다. 예를 들어, 모델을 ONNX 형식으로 내보낼 수 있습니다:from ultralytics import YOLO # Load the YOLO model model = YOLO("yolo26n.pt") # Export the model to ONNX format model.export(format="onnx")다양한 내보내기 옵션에 대해서는 내보내기 모드 문서를 참고하세요.
네, 다른 데이터셋에서 YOLO 모델을 검증할 수 있습니다. 학습 후 검증 모드를 사용하여 성능을 평가할 수 있습니다:
from ultralytics import YOLO # Load a YOLO model model = YOLO("yolo26n.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")자세한 예제와 사용법은 검증 모드 페이지를 확인하세요.