Ultralytics YOLO를 사용한 모델 예측
소개#
머신러닝과 컴퓨터 비전에서 학습된 모델로 시각 데이터를 분석하는 작업을 추론 또는 예측이라고 합니다. Ultralytics YOLO26의 Predict 모드는 다양한 데이터 소스에서 빠른 실시간 추론을 수행합니다.
추론 예시 계획은 미출시 YOLO27 미리보기를 참조하세요.
시청: Python에서 Ultralytics YOLO26으로 바운딩 박스, 마스크, 키포인트, OBB, 깊이 등을 추출하기 🚀
실제 적용 사례#
| 제조 | 스포츠 | 안전 |
|---|---|---|
| 차량 예비 부품 탐지 | 축구 선수 탐지 | 사람 넘어짐 탐지 |
추론에 Ultralytics YOLO를 사용하는 이유#
YOLO26의 Predict 모드를 사용하는 주요 이유:
- 다용성: 이미지, 동영상, 라이브 스트림에서 추론을 실행합니다.
- 성능: 정확도를 저하시키지 않으면서 실시간 고속 처리를 제공하도록 설계되었습니다.
- 간편한 사용: 신속한 배포와 테스트를 위한 직관적인 Python 및 CLI 인터페이스를 제공합니다.
- 높은 사용자 지정 가능성: 특정 요구 사항에 맞게 모델의 추론 동작을 조정할 수 있는 다양한 설정과 매개변수를 제공합니다.
- 프로덕션 배포 준비 완료: 자동 확장 및 모니터링 기능을 갖춘 Ultralytics Platform 추론 엔드포인트로 모델을 배포하거나 로컬에서 추론을 실행할 수 있습니다.
Predict 모드의 주요 기능#
YOLO26 Predict 모드의 기능:
- 다양한 데이터 소스 호환성: Predict 모드는 개별 이미지, 이미지 모음, 동영상 파일, 실시간 동영상 스트림을 입력으로 지원합니다.
- 스트리밍 모드: 스트리밍 기능을 사용하면 메모리 효율적인
Results객체 제너레이터를 생성할 수 있습니다. 예측기의 호출 메서드에서stream=True을 설정하여 이 기능을 활성화합니다. 모든 결과가 포함된 목록을 반환하는 기본 동작(stream=False)과 달리,stream=True은 결과를 한 번에 하나씩 생성하므로 긴 동영상과 실시간 스트림에 특히 유용합니다. - 배치 처리: 여러 이미지나 동영상 프레임을 단일 배치로 처리해 전체 추론 시간을 더 단축합니다.
- 간편한 통합: 유연한 API를 통해 기존 데이터 파이프라인 및 기타 소프트웨어 구성 요소와 통합할 수 있습니다.
Ultralytics YOLO 모델은 추론 시 모델에 stream=True를 전달하면 Results 객체의 Python 목록 또는 메모리 효율적인 Results 객체 제너레이터를 반환합니다.
from ultralytics import YOLO
# 모델 로드
model = YOLO("yolo26n.pt") # 사전 학습된 YOLO26n 모델
# 이미지 목록에 대해 배치 추론 실행
results = model(["image1.jpg", "image2.jpg"]) # Results 객체 목록 반환
# 결과 목록 처리
for result in results:
boxes = result.boxes # 바운딩 박스 출력을 위한 Boxes 객체
masks = result.masks # 세그멘테이션 마스크 출력을 위한 Masks 객체
keypoints = result.keypoints # 포즈 출력을 위한 Keypoints 객체
probs = result.probs # 분류 출력을 위한 Probs 객체
obb = result.obb # OBB 출력을 위한 방향 지정 박스 객체
result.show() # 화면에 표시
result.save(filename="result.jpg") # 디스크에 저장추론 소스#
YOLO26은 아래 표와 같이 다양한 유형의 입력 소스를 추론에 사용할 수 있습니다. 소스에는 정적 이미지, 동영상 스트림 및 다양한 데이터 형식이 포함됩니다. 또한 각 소스를 stream=True ✅ 인수를 사용하는 스트리밍 모드에서 사용할 수 있는지도 표에 표시되어 있습니다. 스트리밍 모드는 모든 프레임을 메모리에 로드하는 대신 결과 제너레이터를 생성하므로 동영상이나 실시간 스트림 처리에 유용합니다.
긴 동영상이나 대규모 데이터 세트를 처리할 때는 메모리를 효율적으로 관리하기 위해 stream=True을 사용합니다. stream=False인 경우 모든 프레임 또는 데이터 포인트의 결과가 메모리에 저장되므로, 대용량 입력에서는 메모리 사용량이 빠르게 증가해 메모리 부족 오류가 발생할 수 있습니다. 반면 stream=True는 현재 프레임 또는 데이터 포인트의 결과만 메모리에 유지하는 제너레이터를 사용하므로 메모리 사용량을 크게 줄이고 메모리 부족 문제를 방지합니다.
| 소스 | 예시 | 유형 | 참고 |
|---|---|---|---|
| 이미지 | 'image.jpg' | str 또는 Path | 단일 이미지 파일입니다. |
| URL | 'https://ultralytics.com/images/bus.jpg' | str | 이미지 URL입니다. |
| 스크린샷 ✅ | 'screen' | str | 중지할 때까지 화면을 계속 캡처합니다. |
| PIL | Image.open('image.jpg') | PIL.Image | RGB 채널의 HWC 형식입니다. |
| OpenCV | cv2.imread('image.jpg') | np.ndarray | BGR 채널의 HWC 형식 uint8 (0-255)입니다. |
| NumPy | np.zeros((640,1280,3)) | np.ndarray | BGR 채널의 HWC 형식 uint8 (0-255)입니다. |
| torch | torch.zeros(16,3,320,640) | torch.Tensor | RGB 채널의 BCHW 형식 float32 (0.0-1.0)입니다. |
| CSV | 'sources.csv' | str 또는 Path | 이미지, 동영상 또는 디렉터리 경로가 포함된 CSV 파일입니다. |
| 동영상 ✅ | 'video.mp4' | str 또는 Path | MP4, AVI 등의 형식으로 된 동영상 파일입니다. |
| 디렉터리 ✅ | 'path/' | str 또는 Path | 이미지 또는 동영상이 포함된 디렉터리 경로입니다. |
| glob ✅ | 'path/*.jpg' | str | 여러 파일을 일치시키는 Glob 패턴입니다. 와일드카드로 * 문자를 사용합니다. |
| YouTube ✅ | 'https://youtu.be/LNwODJXcvt4' | str | YouTube 동영상 URL입니다. |
| 스트림 ✅ | 'rtsp://example.com/media.mp4' | str | RTSP, RTMP, TCP 등의 스트리밍 프로토콜 URL 또는 IP 주소입니다. |
| 멀티 스트림 ✅ | 'list.streams' | str 또는 Path | 각 행에 스트림 URL 하나가 포함된 *.streams 텍스트 파일입니다. 예를 들어 스트림 8개를 배치 크기 8로 실행합니다. |
| 웹캠 ✅ | 0 | int | 추론을 실행할 연결된 카메라 장치의 인덱스입니다. |
각 소스 유형을 사용하는 코드 예시는 다음과 같습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n 모델 로드
model = YOLO("yolo26n.pt")
# 이미지 파일 경로 정의
source = "path/to/image.jpg"
# 소스에서 추론 실행
results = model(source) # Results 객체 목록추론 인수#
model.predict()은 추론 시 기본값을 재정의하기 위해 전달할 수 있는 여러 인수를 지원합니다:
고정 형태와 최소 사각형(rect)#
기본적으로 predict는 rect=True을 사용하며, 가능한 경우 최소 직사각형 패딩을 적용합니다. 이미지가 imgsz 안에 맞도록 크기가 조정되고 가장 가까운 stride 배수까지만 패딩되므로 최종 텐서는 imgsz보다 작을 수 있습니다. 최소 직사각형 패딩은 배치의 모든 이미지가 동일한 형태이고 백엔드가 이를 지원하는 경우에만 사용됩니다(PyTorch .pt 또는 동적 ONNX와 같은 동적 형태 내보내기). 그렇지 않으면 이미지에 전체 imgsz 대상 크기까지 패딩합니다. Depth 및 RT-DETR 모델은 rect를 무시하고 패딩 없이 모든 이미지를 전체 imgsz 크기로 늘립니다.
전체 imgsz 대상 크기를 항상 사용하려면 rect=False을 사용하세요. 내보낸 모델(ONNX, TensorRT 등)과 일치하도록 고정 입력 크기가 필요한 경우 이 방법을 권장합니다.
정수와 튜플 imgsz
- 정수
imgsz=640은 stride 반올림 후 정사각형 대상 크기(640, 640)이 됩니다. - 튜플
imgsz=(384, 672)은 직사각형 대상 크기를 설정합니다.rect=True을 사용하면 실제 텐서가 이 대상 크기보다 작을 수 있습니다.
학습과 predict/export
학습에서는 단일 정수 imgsz만 지원합니다([h, w] 목록은 가장 큰 값으로 변환됩니다). Predict와 export에서는 정수 또는 (height, width) 튜플을 사용할 수 있습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n 모델 로드
model = YOLO("yolo26n.pt")
# 'bus.jpg'에서 인수를 사용해 추론 실행
model.predict("https://ultralytics.com/images/bus.jpg", save=True, imgsz=320, conf=0.25)추론 인수:
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
source | str 또는 int 또는 None | None | 추론할 데이터 소스를 지정합니다. 이미지 경로, 동영상 파일, 디렉터리, URL 또는 라이브 피드용 장치 ID를 지정할 수 있습니다. 생략하면 경고가 로그에 기록되고 모델은 기본 제공 데모 에셋(ultralytics/assets 또는 OBB용 데모 URL)을 사용합니다. 다양한 형식과 소스를 지원하여 다양한 유형의 입력에 유연하게 적용할 수 있습니다. |
conf | float | 0.25 | 감지의 최소 신뢰도 임계값을 설정합니다. 신뢰도가 이 임계값보다 낮은 객체는 무시됩니다. 이 값을 조정하면 오탐을 줄일 수 있습니다. |
iou | float | 0.5 | 비최대 억제(NMS)에 적용되는 교집합 대비 합집합(IoU) 임계값입니다. 값을 낮추면 겹치는 박스를 제거하여 감지 수가 줄어들므로 중복을 줄이는 데 유용합니다. |
imgsz | int 또는 tuple | 640 | 레터박스 목표 크기입니다. 정수는 정사각형 N×N을 지정하고, 튜플은 (height, width)을 지정합니다. rect=True를 사용하면 최소 직사각형 패딩으로 인해 실제 텐서가 목표 크기보다 작을 수 있습니다. 고정 크기를 사용하려면 rect=False을 지정하세요. 고정 형식과 최소 직사각형 비교를 참조하세요. |
rect | bool | True | True인 경우, 가능한 경우 최소 직사각형 패딩을 사용합니다(동일한 형태의 배치 및 지원되는 백엔드). False인 경우, 항상 전체 imgsz를 사용합니다. 고정 형태와 최소 직사각형 비교를 참조하세요. depth 및 RT-DETR 모델에서는 이 설정이 무시되며, 패딩 없이 이미지를 전체 imgsz 크기로 늘립니다. |
quantize | int 또는 str | None | 추론 정밀도: 16/"fp16" 및 32/"fp32"/unset은 PyTorch 및 TorchScript 모델의 FP16 또는 FP32 연산을 선택합니다(CPU에서는 FP32). 다른 형식은 아티팩트와 런타임이 선택하는 정밀도를 사용합니다. 16에서는 OpenVINO가 여전히 클라이언트에서 입력을 FP16으로 반올림한 뒤 FP32로 다시 확장하며, 런타임 정밀도는 변경하지 않습니다. INT8/PTQ 양자화는 내보내기 중에 구성한 다음, 내보낸 모델을 로드하여 사용합니다. 더 이상 사용되지 않는 half 플래그를 대체합니다. |
device | str | None | 추론에 사용할 장치를 지정합니다(예: cpu, cuda:0, 0, npu 또는 npu:0). 사용자는 모델 실행에 사용할 CPU, 특정 GPU, Huawei Ascend NPU 또는 기타 컴퓨팅 장치를 선택할 수 있습니다. OpenVINO 및 LiteRT 모델은 Intel GPU와 NPU에서 xpu 및 npu을 실행합니다. 모든 형식에 대한 자세한 내용은 추론 장치를 참조하세요. |
dnn | bool | False | True이면 ONNX 모델 추론에 ONNX Runtime 대신 OpenCV DNN 모듈을 사용합니다. |
data | str | None | 데이터셋 YAML 경로(예: coco8.yaml)입니다. YAML은 names에 대해서만 읽으며, 로드된 모델에 자체 클래스 이름이 없는 경우에만 사용됩니다. 여기에 해당하는 모델은 타사에서 내보낸 모델이거나, 함께 제공되는 메타데이터와 분리된 Ultralytics 내보내기 모델입니다. 그렇지 않은 경우 이러한 모델은 class0, class1 등을 보고합니다. |
batch | int | 1 | 추론 배치 크기를 지정합니다(소스가 디렉터리, 비디오 파일 또는 .txt 파일인 경우에만 작동합니다). 배치 크기를 늘리면 처리량이 향상되어 추론에 필요한 전체 시간이 단축될 수 있습니다. |
tile | bool 또는 int | False | 고정 타일 추론을 실행하고 원본 이미지 좌표로 결과를 반환합니다. True은 imgsz을 사용하며, 양의 정수는 타일 크기를 설정합니다. 고해상도 타일링을 참조하세요. |
max_det | int | 300 | 이미지당 허용되는 최대 감지 수입니다. 한 번의 추론에서 모델이 감지할 수 있는 객체의 총수를 제한하여 밀집된 장면에서 출력이 지나치게 많아지는 것을 방지합니다. |
vid_stride | int | 1 | 비디오 입력의 프레임 간격입니다. 시간 해상도를 낮추는 대신 비디오의 프레임을 건너뛰어 처리 속도를 높입니다. 값이 1이면 모든 프레임을 처리하고, 더 큰 값이면 프레임을 건너뜁니다. |
stream_buffer | bool | False | 비디오 스트림의 입력 프레임을 대기열에 넣을지 결정합니다. False이면 새 프레임을 수용하기 위해 오래된 프레임을 삭제합니다(실시간 애플리케이션에 최적화됨). True이면 새 프레임을 버퍼에 대기시켜 프레임을 건너뛰지 않지만, 추론 FPS가 스트림 FPS보다 낮으면 지연이 발생합니다. |
visualize | bool | False | 각 예측 결과 옆에 클래스 활성화 히트맵을 저장하여 예측 클래스 점수를 높인 픽셀을 표시합니다. conf 및 classes을 따르므로 classes=[0]는 해당 클래스만 매핑합니다. Ultralytics PyTorch 모델에서만 사용할 수 있습니다. |
augment | bool | False | 예측에 테스트 시점 증강(TTA)을 적용하여 추론 속도가 느려질 수 있는 대신 감지 견고성을 높입니다. Ultralytics PyTorch 모델에서만 사용할 수 있습니다. |
agnostic_nms | bool | False | 클래스 구분 없는 비최대 억제(NMS)를 활성화하여 같은 클래스 내에서만 억제하는 대신 서로 다른 클래스에 걸친 겹치는 상자 중 점수가 낮은 상자를 억제합니다. 클래스 간 중첩이 흔한 다중 클래스 감지 시나리오에 유용합니다. NMS가 없는 추론(YOLO26 또는 YOLOv10에서 nms=False)에서는 동일한 감지가 여러 클래스 레이블로 나타나는 것(IoU=1.0 중복)만 방지하며, 서로 다른 상자 간 IoU 임계값 기반 억제는 수행하지 않습니다. |
classes | list[int] | None | 예측 결과를 클래스 ID 집합으로 필터링합니다. 지정된 클래스에 속하는 감지만 반환합니다. 다중 클래스 감지 작업에서 관련 객체에 집중할 때 유용합니다. |
retina_masks | bool | False | 고해상도 분할 마스크를 반환합니다. 활성화하면 반환된 마스크(masks.data)가 원본 이미지 크기와 일치합니다. 비활성화하면 추론에 사용된 이미지 크기의 마스크를 반환합니다. |
embed | list[int] | None | 특징 벡터 또는 임베딩을 추출할 레이어를 지정합니다. model.embed(source)은 끝에서 두 번째 레이어의 임베딩을 사용하고, model.predict(source, embed=[layer])는 특정 레이어를 선택합니다. 클러스터링이나 유사도 검색과 같은 다운스트림 작업에 유용합니다. Ultralytics PyTorch 모델에서만 사용할 수 있습니다. |
project | str | None | save이 활성화된 경우 예측 출력이 저장되는 프로젝트 디렉터리의 이름입니다. 상대 경로는 runs_dir/<task> 아래에 지정되며, 절대 경로는 입력한 그대로 사용됩니다. |
name | str | None | 예측 실행의 이름입니다. save이 활성화된 경우 프로젝트 폴더 안에 하위 디렉터리를 만들어 예측 출력을 저장하는 데 사용됩니다. |
stream | bool | False | 모든 프레임을 한꺼번에 메모리에 로드하는 대신 Results 객체의 생성기를 반환하여 긴 비디오나 다수의 이미지를 메모리 효율적으로 처리합니다. |
verbose | bool | True | 터미널에 자세한 추론 로그를 표시할지 제어하여 예측 과정에 대한 실시간 피드백을 제공합니다. |
compile | bool 또는 str | False | backend='inductor'을 사용하여 PyTorch 2.x torch.compile 그래프 컴파일을 활성화합니다. True → "default", False → 비활성화, 또는 "default", "reduce-overhead", "max-autotune-no-cudagraphs"과 같은 문자열 모드를 지정할 수 있습니다. 지원되지 않으면 경고를 표시하고 eager 모드로 대체합니다. |
channels_last | bool | None | 네이티브 PyTorch 추론에 channels_last(NHWC) 메모리 형식을 사용합니다. None은 PyTorch 1.13 이상을 사용하는 oneDNN 지원 Linux 및 Windows x86 CPU에서 자동으로 활성화하고, False은 비활성화하며, True는 지원되는 x86 CPU 또는 CUDA 장치에서 사용하도록 요청합니다. ARM64, MPS, 이전 PyTorch 버전, oneDNN을 지원하지 않는 CPU, TensorRT 및 ONNX와 같은 내보내기 형식은 변경되지 않습니다. |
nms | bool, 선택 사항 | None | 기본적으로 NMS를 적용하는 일대다 추론을 실행합니다(None 또는 True). 사용 가능한 경우 NMS가 없는 일대일 헤드를 사용하려면 False로 설정합니다. 자세한 내용은 엔드투엔드 감지 가이드를 참조하세요. |
시각화 인수:
| 인수 | 유형 | 기본값 | 설명 |
|---|---|---|---|
show | bool | False | True이면 주석이 추가된 이미지나 비디오를 창에 표시합니다. 개발 또는 테스트 중 즉각적인 시각적 피드백을 얻는 데 유용합니다. |
save | bool | False or True | 주석이 추가된 이미지나 비디오를 파일로 저장합니다. 문서화, 추가 분석 또는 결과 공유에 유용합니다. CLI 사용 시 기본값은 True이고, Python에서 사용 시 기본값은 False입니다. |
save_frames | bool | False | 비디오를 처리할 때 개별 프레임을 이미지로 저장합니다. 특정 프레임 추출이나 프레임별 상세 분석에 유용합니다. |
save_txt | bool | False | 감지 결과를 [class] [x_center] [y_center] [width] [height] [confidence] 형식에 따라 텍스트 파일로 저장합니다. 다른 분석 도구와 통합할 때 유용합니다. |
save_conf | bool | False | 저장된 텍스트 파일에 신뢰도 점수를 포함합니다. 후처리 및 분석에 사용할 수 있는 세부 정보가 늘어납니다. |
save_crop | bool | False | 감지된 객체의 크롭 이미지를 저장합니다. 데이터셋 증강, 분석 또는 특정 객체에 집중한 데이터셋 생성에 유용합니다. |
show_labels | bool | True | 시각화 출력에 각 감지 결과의 레이블을 표시합니다. 감지된 객체를 즉시 파악할 수 있습니다. |
show_conf | bool | True | 각 감지 결과의 레이블 옆에 신뢰도 점수를 표시합니다. 각 감지 결과에 대한 모델의 확신도를 파악할 수 있습니다. |
show_boxes | bool | True | 감지된 객체 주위에 경계 상자를 그립니다. 이미지나 비디오 프레임에서 객체를 시각적으로 식별하고 위치를 파악하는 데 필수적입니다. |
line_width | int or None | None | 경계 상자의 선 너비를 지정합니다. None이면 이미지 크기에 따라 선 너비를 자동으로 조정합니다. 가독성을 높이기 위해 시각적 설정을 사용자 지정할 수 있습니다. |
추론 장치#
device은 모든 모델 형식에서 PyTorch 장치 이름을 사용하므로, .pt 체크포인트를 실행하든 내보낸 모델을 실행하든 같은 값으로 같은 하드웨어를 선택합니다. 값을 지정하지 않으면 사용 가능한 최적의 장치를 사용합니다. 각 런타임은 장치 이름을 자체 하드웨어에 매핑하며, 검증과 벤치마킹에도 같은 값을 사용합니다.
| 형식 | 지정하지 않음 | cpu | 0 또는 cuda:0 | mps | xpu | npu |
|---|---|---|---|---|---|---|
PyTorch .pt, TorchScript | CUDA GPU, 그렇지 않으면 CPU | CPU | NVIDIA GPU | Apple GPU | Intel GPU | Huawei Ascend NPU |
| ONNX | CUDA GPU, 그렇지 않으면 CPU | CPU | NVIDIA GPU(CUDA), AMD GPU(MIGraphX) | Core ML | - | - |
| TensorRT | NVIDIA GPU | NVIDIA GPU | NVIDIA GPU | - | - | - |
| OpenVINO | OpenVINO AUTO | Intel CPU | - | - | Intel GPU(xpu:1은 OpenVINO GPU.1임) | Intel NPU |
| LiteRT | CPU | CPU | - | - | OpenVINO 플러그인을 통한 Intel GPU | OpenVINO 플러그인을 통한 Intel NPU |
| PaddlePaddle | CUDA GPU, 그렇지 않으면 CPU | CPU | NVIDIA GPU | - | - | - |
-은 런타임에 해당 장치용 백엔드가 없음을 의미합니다. ONNX, TensorRT 및 PaddlePaddle은 먼저 PyTorch로 장치 이름을 확인하므로, PyTorch에서 인식할 수 없는 장치는 거부하고 인식할 수 있는 장치는 기본 하드웨어에서 실행합니다. OpenVINO는 요청한 Intel 장치를 찾을 수 없으면 경고를 표시하고 AUTO로 대체하며, LiteRT Intel 플러그인은 CPU로 대체합니다. 다른 형식은 각자의 하드웨어를 선택합니다. CoreML은 Apple Neural Engine과 CPU에서 실행되고, Edge TPU는 tpu:0을 사용하며, NCNN은 Vulkan GPU 경로에 vulkan:0를 사용하고, 나머지 형식은 대상 장치의 CPU 또는 가속기에서 실행됩니다. 이전의 intel:cpu, intel:gpu, intel:npu 이름은 cpu, xpu, npu의 지원 중단된 별칭으로 계속 사용할 수 있습니다.
from ultralytics import YOLO
model = YOLO("yolo26n_openvino_model/")
results = model("https://ultralytics.com/images/bus.jpg", device="npu") # Intel NPU이미지 및 동영상 형식#
YOLO26은 ultralytics/data/utils.py에 명시된 다양한 이미지 및 동영상 형식을 지원합니다. 유효한 접미사와 predict 명령 예시는 아래 표를 참조하세요.
이미지#
아래 표에는 유효한 Ultralytics 이미지 형식이 나와 있습니다.
HEIC/HEIF 형식을 사용하려면 pi-heif이 필요하며, 처음 사용할 때 자동으로 설치됩니다. AVIF는 Pillow에서 기본적으로 지원됩니다.
| 이미지 접미사 | Predict 명령 예시 | 참조 |
|---|---|---|
.avif | yolo predict source=image.avif | AV1 이미지 파일 형식 |
.bmp | yolo predict source=image.bmp | Microsoft BMP 파일 형식 |
.dng | yolo predict source=image.dng | Adobe DNG |
.heic | yolo predict source=image.heic | 고효율 이미지 파일 형식 |
.heif | yolo predict source=image.heif | 고효율 이미지 파일 형식 |
.jp2 | yolo predict source=image.jp2 | JPEG 2000 |
.jpeg | yolo predict source=image.jpeg | JPEG |
.jpg | yolo predict source=image.jpg | JPEG |
.mpo | yolo predict source=image.mpo | 다중 사진 객체 |
.png | yolo predict source=image.png | 휴대용 네트워크 그래픽 |
.tif | yolo predict source=image.tif | 태그 이미지 파일 형식 |
.tiff | yolo predict source=image.tiff | 태그 이미지 파일 형식 |
.webp | yolo predict source=image.webp | WebP |
동영상#
아래 표에는 유효한 Ultralytics 동영상 형식이 나와 있습니다.
| 동영상 접미사 | Predict 명령 예시 | 참조 |
|---|---|---|
.asf | yolo predict source=video.asf | 고급 시스템 형식 |
.avi | yolo predict source=video.avi | 오디오 비디오 인터리브 |
.gif | yolo predict source=video.gif | 그래픽 교환 형식 |
.m4v | yolo predict source=video.m4v | MPEG-4 Part 14 |
.mkv | yolo predict source=video.mkv | Matroska |
.mov | yolo predict source=video.mov | QuickTime 파일 형식 |
.mp4 | yolo predict source=video.mp4 | MPEG-4 Part 14 - 위키백과 |
.mpeg | yolo predict source=video.mpeg | MPEG-1 Part 2 |
.mpg | yolo predict source=video.mpg | MPEG-1 Part 2 |
.ts | yolo predict source=video.ts | MPEG 전송 스트림 |
.wmv | yolo predict source=video.wmv | Windows Media Video |
.webm | yolo predict source=video.webm | WebM 프로젝트 |
Results 사용#
모든 Ultralytics predict() 호출은 Results 객체 목록을 반환합니다:
from ultralytics import YOLO
# 사전 학습된 YOLO26n 모델 로드
model = YOLO("yolo26n.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/bus.jpg")
results = model(
[
"https://ultralytics.com/images/bus.jpg",
"https://ultralytics.com/images/zidane.jpg",
]
) # 배치 추론Results 객체에는 다음 속성이 있습니다:
| 속성 | 유형 | 설명 |
|---|---|---|
orig_img | np.ndarray | 원본 이미지의 NumPy 배열입니다. |
orig_shape | tuple | (높이, 너비) 형식의 원본 이미지 형태입니다. |
boxes | Boxes, optional | 탐지 바운딩 박스가 포함된 Boxes 객체입니다. |
masks | Masks, optional | 탐지 마스크가 포함된 Masks 객체입니다. |
probs | Probs, optional | 분류 작업의 각 클래스 확률이 포함된 Probs 객체입니다. |
keypoints | Keypoints, optional | 각 객체에서 탐지된 키포인트가 포함된 Keypoints 객체입니다. |
obb | OBB, optional | 방향이 있는 바운딩 박스가 포함된 OBB 객체입니다. |
semantic_mask | SemanticMask, optional | 픽셀별 조밀한 클래스 맵이 포함된 SemanticMask 객체입니다. |
depth | DepthMap, optional | 픽셀별 조밀한 깊이 맵이 포함된 DepthMap 객체입니다. |
speed | dict | 이미지당 밀리초 단위의 전처리, 추론 및 후처리 속도 사전입니다. |
names | dict | 클래스 인덱스를 클래스 이름에 매핑하는 사전입니다. |
path | str | 이미지 파일의 경로입니다. |
save_dir | str, optional | 결과를 저장할 디렉터리입니다. |
작업별 Results#
아래 필드의 값은 모델의 task에 따라 다릅니다. 아직 task를 선택하지 않았다면 객체 감지, 세그멘테이션, 시맨틱 세그멘테이션, 깊이 추정, 분류, 자세 추정, OBB 비교를 참조하세요. 각 예측은 이미지 또는 프레임당 Results 객체 하나를 반환합니다. 위의 공통 필드는 항상 사용할 수 있으며, task별 예측 데이터는 아래 필드에 저장됩니다. YOLO 좌표 및 confidence 텐서는 torch.float32입니다. 확률 텐서는 모델이 FP16으로 실행되는 경우(quantize=16를 사용하는 PyTorch 또는 CPU 외부에서 실행되는 TorchScript 모델, 또는 FP16 입력을 사용하는 ONNX 모델)가 아니라면 torch.float32이며, 해당 경우에는 torch.float16입니다. result.numpy() 이후 텐서는 해당 NumPy dtype과 일치하는 NumPy 배열이 됩니다. 인스턴스 마스크는 torch.uint8 이진 텐서이며, 시맨틱 마스크는 클래스 수에 따라 클래스 ID에 적합한 가장 작은 정수 dtype인 torch.uint8, torch.int16 또는 torch.int32을 사용합니다.
| 속성 | 유형 | 형태 | 설명 |
|---|---|---|---|
result.boxes | Boxes | (N) | 탐지 박스입니다. |
result.boxes.data | torch.float32 | (N,6/7) | 원시 [x1,y1,x2,y2,conf,cls]이며, 선택적으로 트랙 ID가 포함됩니다. |
result.boxes.xyxy | torch.float32 | (N,4) | xyxy 픽셀 박스입니다. |
result.boxes.conf | torch.float32 | (N,) | 신뢰도 점수입니다. |
result.boxes.cls | torch.float32 | (N,) | 클래스 ID이며, 이름을 가져오려면 int으로 변환합니다. |
Results 객체에는 다음 메서드가 있습니다.
| 메서드 | 반환 유형 | 설명 |
|---|---|---|
update() | None | 박스, 마스크, 확률값, OBB, 키포인트, 시맨틱 마스크 또는 깊이와 같은 새 데이터로 Results 객체를 업데이트합니다. |
cpu() | Results | 모든 텐서를 CPU 메모리로 이동한 Results 객체의 복사본을 반환합니다. |
numpy() | Results | 모든 텐서를 NumPy 배열로 변환한 Results 객체의 복사본을 반환합니다. |
cuda() | Results | 모든 텐서를 GPU 메모리로 이동한 Results 객체의 복사본을 반환합니다. |
to() | Results | 텐서를 지정된 디바이스와 dtype으로 이동한 Results 객체의 복사본을 반환합니다. |
new() | Results | 동일한 이미지, 경로, 이름 및 속도 속성을 가진 새 Results 객체를 생성합니다. |
plot() | np.ndarray | 입력 BGR 이미지에 탐지 결과를 그린 후 주석이 추가된 이미지를 반환합니다. |
show() | None | 추론 결과에 주석이 추가된 이미지를 표시합니다. |
save() | str | 추론 결과에 주석이 추가된 이미지를 파일로 저장하고 파일 이름을 반환합니다. |
verbose() | str | 각 태스크의 탐지 및 분류 결과를 자세히 설명하는 로그 문자열을 반환합니다. |
save_txt() | str | 탐지 결과를 텍스트 파일로 저장하고 저장된 파일의 경로를 반환합니다. |
save_crop() | None | 탐지된 이미지의 크롭본을 지정된 디렉터리에 저장합니다. |
summary() | List[Dict[str, Any]] | 추론 결과를 선택적으로 정규화하여 요약된 딕셔너리로 변환합니다. |
to_df() | DataFrame | 탐지 결과를 Polars DataFrame으로 변환합니다. |
to_csv() | str | 탐지 결과를 CSV 형식으로 변환합니다. |
to_json() | str | 탐지 결과를 JSON 형식으로 변환합니다. |
자세한 내용은 Results 클래스 문서를 참조하세요.
박스#
Boxes 객체를 사용하여 바운딩 박스를 인덱싱하고 조작하거나 다른 형식으로 변환할 수 있습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n 모델 로드
model = YOLO("yolo26n.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/bus.jpg") # 결과 목록
# 결과 보기
for r in results:
print(r.boxes) # 탐지 바운딩 박스가 포함된 Boxes 객체를 print합니다다음은 이름, 유형 및 설명을 포함한 Boxes 클래스 메서드와 속성의 표입니다.
| 이름 | 유형 | 설명 |
|---|---|---|
cpu() | 메서드 | 객체를 CPU 메모리로 이동합니다. |
numpy() | 메서드 | 객체를 NumPy 배열로 변환합니다. |
cuda() | 메서드 | 객체를 CUDA 메모리로 이동합니다. |
to() | 메서드 | 객체를 지정된 디바이스로 이동합니다. |
xyxy | 속성 (torch.Tensor) | 박스를 xyxy 형식으로 반환합니다. |
conf | 속성 (torch.Tensor) | 박스의 신뢰도 값을 반환합니다. |
cls | 속성 (torch.Tensor) | 박스의 클래스 값을 반환합니다. |
id | 속성 (torch.Tensor) | 박스의 트랙 ID를 반환합니다(사용 가능한 경우). |
xywh | 속성 (torch.Tensor) | 박스를 xywh 형식으로 반환합니다. |
xyxyn | 속성 (torch.Tensor) | 원본 이미지 크기로 정규화된 박스를 xyxy 형식으로 반환합니다. |
xywhn | 속성 (torch.Tensor) | 원본 이미지 크기로 정규화된 박스를 xywh 형식으로 반환합니다. |
자세한 내용은 Boxes 클래스 문서를 참조하세요.
마스크#
Masks 객체를 사용하여 마스크를 인덱싱하고 조작하거나 세그먼트로 변환할 수 있습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n-seg 세그먼트 모델 로드
model = YOLO("yolo26n-seg.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/bus.jpg") # 결과 목록
# 결과 보기
for r in results:
print(r.masks) # 탐지된 인스턴스 마스크가 포함된 Masks 객체를 print합니다다음은 이름, 유형 및 설명을 포함한 Masks 클래스 메서드와 속성의 표입니다.
| 이름 | 유형 | 설명 |
|---|---|---|
data | 속성 (torch.Tensor) | torch.uint8 이진 마스크 텐서로, 형태는 (N,H,W)이고 값은 0 또는 1입니다. |
cpu() | 메서드 | CPU 메모리에 있는 마스크 텐서를 반환합니다. |
numpy() | 메서드 | 마스크 텐서를 NumPy 배열로 반환합니다. |
cuda() | 메서드 | GPU 메모리에 있는 마스크 텐서를 반환합니다. |
to() | 메서드 | 지정된 디바이스와 dtype을 사용하는 마스크 텐서를 반환합니다. |
xyn | 속성 (list[np.ndarray]) | 정규화된 마스크 폴리곤 목록입니다. |
xy | 속성 (list[np.ndarray]) | 픽셀 좌표의 마스크 폴리곤 목록입니다. |
자세한 내용은 Masks 클래스 문서를 참조하세요.
SemanticMask#
SemanticMask은 시맨틱 세그멘테이션 결과를 위한 조밀한 클래스 맵 하나를 저장합니다. Masks과 달리 객체별 이진 마스크를 포함하지 않으며 폴리곤 헬퍼도 제공하지 않습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n-sem 시맨틱 모델 로드
model = YOLO("yolo26n-sem.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/bus.jpg") # 결과 목록
# 결과 보기
for r in results:
print(r.semantic_mask.data) # H x W 클래스 ID 맵을 print합니다| 이름 | 유형 | 설명 |
|---|---|---|
data | 속성 (torch.Tensor) | 형태가 (H,W)인 클래스 ID 맵입니다. dtype은 클래스 수에 따라 torch.uint8, torch.int16 또는 torch.int32으로 선택됩니다. |
shape | 속성 (tuple) | 클래스 맵의 형태로, 일반적으로 result.orig_shape과 일치합니다. |
cpu() | 메서드 | CPU 메모리에 있는 시맨틱 마스크 텐서를 반환합니다. |
numpy() | 메서드 | 시맨틱 마스크 텐서를 NumPy 배열로 반환합니다. |
cuda() | 메서드 | GPU 메모리에 있는 시맨틱 마스크 텐서를 반환합니다. |
to() | 메서드 | 지정된 디바이스와 dtype을 사용하는 시맨틱 마스크 텐서를 반환합니다. |
키포인트#
Keypoints 객체를 사용하여 좌표를 인덱싱하고 조작하거나 정규화할 수 있습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n-pose 포즈 모델 로드
model = YOLO("yolo26n-pose.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/bus.jpg") # 결과 목록
# 결과 보기
for r in results:
print(r.keypoints) # 탐지된 키포인트가 포함된 Keypoints 객체를 print합니다다음은 이름, 유형 및 설명을 포함한 Keypoints 클래스 메서드와 속성의 표입니다.
| 이름 | 유형 | 설명 |
|---|---|---|
cpu() | 메서드 | CPU 메모리에 있는 키포인트 텐서를 반환합니다. |
numpy() | 메서드 | 키포인트 텐서를 NumPy 배열로 반환합니다. |
cuda() | 메서드 | GPU 메모리에 있는 키포인트 텐서를 반환합니다. |
to() | 메서드 | 지정된 디바이스와 dtype을 사용하는 키포인트 텐서를 반환합니다. |
xyn | 속성 (torch.Tensor) | 형태가 (N,K,2)인 정규화된 키포인트 좌표입니다. |
xy | 속성 (torch.Tensor) | 형태가 (N,K,2)인 픽셀 단위 키포인트 좌표입니다. |
conf | 속성 (torch.Tensor) | 사용 가능한 경우 키포인트의 신뢰도 값을 반환하고, 그렇지 않으면 None을 반환합니다. |
자세한 내용은 Keypoints 클래스 문서를 참조하세요.
확률값#
Probs 객체를 사용하여 top1 분류 인덱스와 top5 점수를 가져올 수 있습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n-cls 분류 모델 로드
model = YOLO("yolo26n-cls.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/bus.jpg") # 결과 목록
# 결과 보기
for r in results:
print(r.probs) # 탐지된 클래스 확률이 포함된 Probs 객체를 print합니다다음은 Probs 클래스의 메서드와 속성을 요약한 표입니다.
| 이름 | 유형 | 설명 |
|---|---|---|
cpu() | 메서드 | probs 텐서의 CPU 메모리 복사본을 반환합니다. |
numpy() | 메서드 | probs 텐서의 NumPy 배열 복사본을 반환합니다. |
cuda() | 메서드 | probs 텐서의 GPU 메모리 복사본을 반환합니다. |
to() | 메서드 | 지정된 디바이스와 dtype으로 probs 텐서의 복사본을 반환합니다. |
top1 | 속성 (int) | 상위 1개 클래스의 인덱스입니다. |
top5 | 속성 (list[int]) | 상위 5개 클래스의 인덱스입니다. |
top1conf | 속성 (torch.Tensor) | 상위 1개 클래스의 신뢰도입니다. |
top5conf | 속성 (torch.Tensor) | 상위 5개 클래스의 신뢰도입니다. |
자세한 내용은 Probs 클래스 문서를 참조하세요.
OBB#
OBB 객체를 사용하여 방향 경계 상자를 인덱싱하고 조작하며 다양한 형식으로 변환할 수 있습니다.
from ultralytics import YOLO
# 사전 학습된 YOLO26n 모델 로드
model = YOLO("yolo26n-obb.pt")
# 이미지에서 추론 실행
results = model("https://ultralytics.com/images/boats.jpg") # 결과 목록
# 결과 보기
for r in results:
print(r.obb) # 방향 탐지 경계 상자를 포함하는 OBB 객체를 출력합니다다음은 이름, 유형 및 설명을 포함한 OBB 클래스 메서드와 속성의 표입니다.
| 이름 | 유형 | 설명 |
|---|---|---|
cpu() | 메서드 | 객체를 CPU 메모리로 이동합니다. |
numpy() | 메서드 | 객체를 NumPy 배열로 변환합니다. |
cuda() | 메서드 | 객체를 CUDA 메모리로 이동합니다. |
to() | 메서드 | 객체를 지정된 디바이스로 이동합니다. |
conf | 속성 (torch.Tensor) | 박스의 신뢰도 값을 반환합니다. |
cls | 속성 (torch.Tensor) | 박스의 클래스 값을 반환합니다. |
id | 속성 (torch.Tensor) | 박스의 트랙 ID를 반환합니다(사용 가능한 경우). |
xyxy | 속성 (torch.Tensor) | 수평 상자를 xyxy 형식으로 반환합니다. |
xywhr | 속성 (torch.Tensor) | 회전된 상자를 xywhr 형식으로 반환합니다. |
xyxyxyxy | 속성 (torch.Tensor) | 회전된 상자를 xyxyxyxy 형식으로 반환합니다. |
xyxyxyxyn | 속성 (torch.Tensor) | 이미지 크기로 정규화한 회전된 상자를 xyxyxyxy 형식으로 반환합니다. |
자세한 내용은 OBB 클래스 문서를 참조하세요.
결과 시각화#
Results 객체의 plot() 메서드는 감지된 객체(예: 경계 상자, 마스크, 키포인트, 확률)를 원본 이미지에 오버레이하여 예측 결과를 시각화합니다. 이 메서드는 주석이 추가된 이미지를 NumPy 배열로 반환하므로 쉽게 표시하거나 저장할 수 있습니다.
from PIL import Image
from ultralytics import YOLO
# Load a pretrained YOLO26n model
model = YOLO("yolo26n.pt")
# Run inference on 'bus.jpg'
results = model(["https://ultralytics.com/images/bus.jpg", "https://ultralytics.com/images/zidane.jpg"]) # results list
# Visualize the results
for i, r in enumerate(results):
# Plot results image
im_bgr = r.plot() # BGR-order numpy array
im_rgb = Image.fromarray(im_bgr[..., ::-1]) # RGB-order PIL image
# Show results to screen (in supported environments)
r.show()
# Save results to disk
r.save(filename=f"results{i}.jpg")plot() 메서드 매개변수#
plot() 메서드는 출력을 사용자 지정할 수 있는 다양한 인수를 지원합니다:
| 인수 | 유형 | 설명 | 기본값 |
|---|---|---|---|
conf | bool | 탐지 신뢰도 점수를 포함합니다. | True |
line_width | float | 경계 상자의 선 너비입니다. None인 경우 이미지 크기에 따라 조정됩니다. | None |
font_size | float | 텍스트 글꼴 크기입니다. None인 경우 이미지 크기에 따라 조정됩니다. | None |
font | str | 텍스트 주석에 사용할 글꼴 이름입니다. | 'Arial.ttf' |
pil | bool | 이미지를 PIL Image 객체로 반환합니다. | False |
img | np.ndarray | torch.Tensor | 대체 이미지입니다. 텐서는 연속된 HWC BGR uint8 형식이어야 합니다. | None |
kpt_radius | int | 그려지는 키포인트의 반지름입니다. | 5 |
kpt_line | bool | 키포인트를 선으로 연결합니다. | True |
labels | bool | 주석에 클래스 레이블을 포함합니다. | True |
boxes | bool | 이미지에 경계 상자를 오버레이합니다. | True |
masks | bool | 이미지에 마스크를 오버레이합니다. | True |
probs | bool | 분류 확률을 포함합니다. | True |
show | bool | 기본 이미지 뷰어를 사용하여 주석이 추가된 이미지를 바로 표시합니다. | False |
save | bool | 주석이 추가된 이미지를 filename으로 지정한 파일에 저장합니다. | False |
filename | str | save이 True인 경우 주석이 추가된 이미지를 저장할 파일의 경로와 이름입니다. | None |
color_mode | str | 색상 모드를 지정합니다(예: 'instance' 또는 'class'). | 'class' |
txt_color | tuple[int, int, int] | 분류 레이블에 사용할 BGR 텍스트 색상입니다. | (255, 255, 255) |
스레드 안전 추론#
서로 다른 스레드에서 여러 YOLO 모델을 병렬로 실행할 때는 추론 중 스레드 안전성을 보장하는 것이 중요합니다. 스레드 안전 추론은 각 스레드의 예측 결과를 격리해 서로 간섭하지 않도록 보장하며, 경쟁 상태를 방지하고 일관되고 신뢰할 수 있는 출력을 제공합니다.
멀티스레드 애플리케이션에서 YOLO 모델을 사용할 때는 충돌을 방지하기 위해 각 스레드에 별도의 모델 객체를 인스턴스화하거나 스레드 로컬 저장소를 사용하는 것이 중요합니다:
스레드 안전 추론을 위해 각 스레드 내부에 단일 모델을 인스턴스화합니다:
from threading import Thread
from ultralytics import YOLO
def thread_safe_predict(model, image_path):
"""Performs thread-safe prediction on an image using a locally instantiated YOLO model."""
model = YOLO(model)
results = model.predict(image_path)
# 결과를 처리합니다
# 각 스레드가 자체 모델 인스턴스를 갖도록 스레드를 시작합니다
Thread(target=thread_safe_predict, args=("yolo26n.pt", "image1.jpg")).start()
Thread(target=thread_safe_predict, args=("yolo26n.pt", "image2.jpg")).start()스트리밍 소스 for 루프#
다음은 OpenCV(cv2)와 YOLO를 사용해 비디오 프레임에서 추론을 실행하는 Python 스크립트입니다. 이 스크립트는 필요한 패키지(opencv-python 및 ultralytics)를 이미 설치했다고 가정합니다.
import cv2
from ultralytics import YOLO
# YOLO 모델 로드
model = YOLO("yolo26n.pt")
# 비디오 파일을 엽니다
video_path = "path/to/your/video/file.mp4"
cap = cv2.VideoCapture(video_path)
# 비디오 프레임을 순회합니다
while cap.isOpened():
# 비디오에서 프레임을 읽습니다
success, frame = cap.read()
if success:
# 프레임에서 YOLO 추론을 실행합니다
results = model(frame)
# 프레임에 결과를 시각화합니다
annotated_frame = results[0].plot()
# 주석이 추가된 프레임을 표시합니다
cv2.imshow("YOLO Inference", annotated_frame)
# 'q'를 누르면 루프를 종료합니다
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
# 비디오 끝에 도달하면 루프를 종료합니다
break
# 비디오 캡처 객체를 해제하고 표시 창을 닫습니다
cap.release()
cv2.destroyAllWindows()이 스크립트는 비디오의 각 프레임에서 예측을 실행하고, 결과를 시각화한 뒤 창에 표시합니다. 'q'를 눌러 루프를 종료할 수 있습니다.
다음 단계#
사전 학습 모델 사용을 넘어 다음 단계로 나아갈 준비가 되셨나요? 작업이 문제에 적합한지 확인하고, 데이터셋 가이드에 따라 데이터를 직접 준비한 다음 모델을 학습시키세요.
자주 묻는 질문#
Ultralytics YOLO는 개별 이미지, 비디오, 디렉터리, URL, 스트림 등 다양한 데이터 소스를 처리할 수 있습니다.
model.predict()호출에서 데이터 소스를 지정할 수 있습니다. 예를 들어 로컬 이미지에는'image.jpg'을, URL에는'https://ultralytics.com/images/bus.jpg'를 사용합니다. 문서에서 다양한 추론 소스에 대한 자세한 예제를 확인하세요.추론 속도를 최적화하고 메모리를 효율적으로 관리하려면 predictor의 호출 메서드에서
stream=True을 설정해 스트리밍 모드를 사용할 수 있습니다. 스트리밍 모드는 모든 프레임을 메모리에 로드하는 대신 메모리 효율적인Results객체 생성기를 생성합니다. 긴 비디오나 대규모 데이터셋을 처리할 때 스트리밍 모드가 특히 유용합니다. 스트리밍 모드에 대해 자세히 알아보세요.YOLO의
model.predict()메서드는conf,iou,imgsz,device등 다양한 인수를 지원합니다. 이러한 인수를 사용하면 신뢰도 임계값, 이미지 크기, 계산에 사용할 디바이스 등의 매개변수를 설정하여 추론 프로세스를 사용자 지정할 수 있습니다. 이러한 인수에 대한 자세한 설명은 추론 인수 섹션에서 확인할 수 있습니다.model.embed(source)을 사용해 끝에서 두 번째 레이어에서 특징 임베딩을 추출하거나, 특정 레이어를 선택하려면embed=[layer_index]을model.predict()에 전달합니다.from ultralytics import YOLO model = YOLO("yolo26n.pt") source = "https://ultralytics.com/images/bus.jpg" results = model.predict(source) # 결과 객체 embeddings = model.embed(source) # torch.Tensor 임베딩 목록YOLO로 추론을 실행한 후
Results객체에는 주석이 추가된 이미지를 표시하고 저장하는 메서드가 포함됩니다.result.show()및result.save(filename="result.jpg")와 같은 메서드를 사용해 결과를 시각화하고 저장할 수 있습니다. 파일 이름 경로에 누락된 상위 디렉터리는 자동으로 생성됩니다(예:result.save("path/to/result.jpg")). 이러한 메서드의 전체 목록은 결과 사용하기 섹션을 참조하세요.
댓글629
질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.
Tigores
你好,我想问一下为什么我在推理相同的图像时,设置不同的imgsz参数,会有不同的结果。在一张图像上,有大船、小船、人。imgsz设置的值有640(默认)、1280、1980。640只能检测到大船;1280会检测到大船和小船,并且大船的置信度更高;1980还能检测到人。我很疑惑,模型的输入尺寸不是在训练的时候就已经固定了吗,这是否意味着推理的图像预处理阶段,不管我如何调整imgsz参数,模型都会将输入图像采样到640。但是现在出现的不同的结果,是为什么呢?下面是我的代码: from ultralytics import YOLO model = YOLO("/data/dxh/ultralytics/weight/yolov8s.pt")
results = model("/data/dxh/ultralytics/datasets/test/invade_ship_cls/invade_result", imgsz=1280, save=True)1
Glenn JocherUltralytics@Tigores 您好!YOLO模型在推理时会自动将输入图像缩放到您指定的imgsz参数值(而非固定为训练尺寸),更大的分辨率能保留更多细节从而提升小目标检测能力。具体原理可参考Predict模式文档中的图像尺寸与精度关系说明,这是预期行为而非异常现象。
LwpZoe
Hello, I would like to ask, my task is instance segmentation. At present, I get the predicted result is the original image superimposed label image, but the result I want is just the RGB label image, no need to superimpose the original image. Where do I need to make changes to make the result a segmented label image?
1
Glenn JocherUltralytics(수정됨)@LwpZoe to obtain only the RGB label image without the original image overlay, you can disable the overlay during visualization. Use the
plot()method withboxes=Falseandmasks=Trueto only display the segmentation masks. Alternatively, you can directly accessresult.masks.datafor raw mask data and process it as needed. Refer to the Results section for more details.LwpZoe
Found plot () in yolo-segment-main/ultralytics/engine/results.py, modified content: Def plot ( Self, Conf = True, line_width = None, font_size = None, Font = "Arial.ttf", Pil = False, Img = None, im_gpu = None, kpt_radius = 5, kpt_line = False, Labels = False, Boxes = False, Masks = True, Probs = True, Show = True, Save = True, Filename = 'result', color_mode = "class", ): Make predictions using the command line: Yolo segment predict model = runs/segment/train/weights/best.pt source=yolo-seg-main/datasets/test The result is still the original image overlay mask and box, why? Does changing plot () require retraining to get best.pt in order to predict?
Glenn JocherUltralyticsTo display only the segmentation mask without overlays, modify the
plot()function parameters by settingboxes=False,labels=False, and ensuringmasks=True. You don't need retraining to adjust visualization settings, as the weights remain unaffected. For further details, refer to the Results.plot() documentation.
UserHello, when I run the predict script, I predict a large amount of image data (about more than 20,000 test images). At this time, the model's predict will get stuck, and I don't generate the image of the prediction box. How can I solve this bug?
1
Paula DerrengerUltralytics@Stephen-Hao it sounds like you might be running into memory issues when processing a large number of images. To handle large datasets more efficiently, consider using the
stream=Trueargument in yourmodel.predict()call. This will create a memory-efficient generator of results, reducing the likelihood of your system getting stuck. Additionally, ensure you are using the latest version of the Ultralytics package to benefit from any recent optimizations and bug fixes. If the issue persists, please provide more details about your environment and any error messages you encounter.
UserYes, Thank you a lot.
Paula DerrengerUltralytics@Stephen-Hao you're welcome! If you're experiencing issues with the model getting stuck while predicting a large number of images, try using the
stream=Trueargument in yourmodel.predict()call. This will help manage memory more efficiently by processing images one at a time instead of loading all at once. Also, ensure you're using the latest version of the Ultralytics package. If the problem persists, please provide more details about your setup and any error messages you encounter.
Johanna-Jones
Hey, Is there a way to get the MAP precision, IOU and other metrics for the test images you might give the model?
I have images and the ground truth for the test images but not sure how to get the same metrics for the PREDICT mode
Thank you!
1Johanna-Jones
For clarification my pipeline is currently train> valid with
valparameter set to false. I then pass one image at a time to the Yolov8 model in the PREDICT mode
Paula DerrengerUltralyticsHey there!
For evaluating your model with metrics like mAP, precision, and IOU on your test images, you should use the
Valmode rather than thePredictmode. TheValmode allows you to validate your model on a dataset and provides comprehensive metrics, including the ones you're interested in. Here's an example on how to do it:from ultralytics import YOLO # Assuming 'coco128.yaml' is your dataset configuration file that includes your test data path # and that 'your_model.pt' is the trained model you want to evaluate model = YOLO('path/to/your_model.pt') # Validate the model, this will automatically calculate mAP, IOU, and other metrics results = model.val(data='path/to/your_dataset_config.yaml')Remember to adjust
'path/to/your_model.pt'and'path/to/your_dataset_config.yaml'to the actual paths of your model and dataset configuration file.In your YAML dataset configuration file, make sure to correctly specify the path to your test images and annotations. This way, YOLOv8 will know how to find your test data and corresponding ground truth for evaluation.
If you have any more questions, feel free to ask. Good luck with your model evaluation! 🚀
GUPABE10
how to ignore printing results after inference: 0: 384x640 10 persons, 1 sports ball, 4080.4ms Speed: 12.3ms preprocess, 4080.4ms inference, 1.7ms postprocess per image at shape (1, 3, 384, 640)
1
Glenn JocherUltralyticsTo disable printing inference results after running predictions, you can use the
verbose=Falseargument in yourpredict()function. This will prevent the printout of inference times and detected objects. Here's a quick example on how to do it:from ultralytics import YOLO # Load your YOLOv8 model model = YOLO('yolov8n.pt') # Run inference with verbose=False results = model.predict('path/to/your/image.jpg', verbose=False)This should keep your console output clean while still performing inference. 😊
GUPABE10
Is it the same if I use:
results = model('path/to/your/image.jpg')
just as mentioned in the example in this tutorial.
Glenn JocherUltralytics@GUPABE10 hi there!
Yes, using
results = model('path/to/your/image.jpg')is perfectly fine and aligns with the examples provided in the tutorial. This command will run inference on the specified image and return the results as a list ofResultsobjects.If you want to avoid printing the detailed inference results (like the number of detected objects and processing times), you can use the
verbose=Falseargument:from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.pt") # Run inference on an image without printing detailed results results = model.predict('path/to/your/image.jpg', verbose=False)This will keep your console output clean while still performing the inference. If you have any more questions or need further assistance, feel free to ask! 😊
GUPABE10
What is the difference between model.predict() and model()?
Glenn JocherUltralyticsHi there!
Great question! The difference between
model.predict()andmodel()lies in their usage and flexibility:-
model.predict():- This method is explicitly designed for running predictions and allows you to pass various arguments to customize the inference process.
- You can specify parameters like
save,imgsz,conf,device, and more to control the behavior of the prediction. - Example:
from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.pt") # Run inference with custom arguments results = model.predict("path/to/image.jpg", save=True, imgsz=320, conf=0.5)
-
model():- This is a shorthand method that calls the
predict()function internally with default settings. - It is useful for quick predictions without needing to specify additional parameters.
- Example:
from ultralytics import YOLO # Load a pretrained YOLOv8n model model = YOLO("yolov8n.pt") # Run inference with default settings results = model("path/to/image.jpg")
- This is a shorthand method that calls the
Both methods will return a list of
Resultsobjects, which you can then process as needed. If you need more control over the prediction process,model.predict()is the way to go. For quick and straightforward predictions,model()is convenient.Feel free to check out the Ultralytics documentation on prediction for more details and examples.
Happy coding! 😊
-
amani784
Hello @glenn-jocher, i have question, my inputs are videos, if i use vid-stride , can i use imgsz with it ?
Glenn JocherUltralyticsYes—
vid_stride(frame skipping) andimgsz(inference resize) are independent, so you can use them together on video sources;imgszwill be applied to the frames that are actually processed (see the Predict mode inference arguments).yolo predict model=yolo26n.pt source=video.mp4 vid_stride=2 imgsz=640from ultralytics import YOLO model = YOLO("yolo26n.pt") for r in model.predict("video.mp4", vid_stride=2, imgsz=640, stream=True): pass1amani784
Thank you for your help. I have another question: if I don’t define imgsz in predict, will it resize the image to 640 by default? I have multiple inputs with different resolutions, so I can’t specify a single value for imgsz in .predict or even during ONNX export, because sometimes the input resolution is larger than imgsz.
Glenn JocherUltralyticsYes—if you don’t pass
imgsztopredict(), it uses the defaultimgsz=640and will letterbox/resize each frame/image to that inference size (so larger inputs are downscaled, smaller are upscaled); for mixed-resolution sources you can either leave the default or set a largerimgszfor more detail (GPU memory permitting) as described in the predict settings defaults.If you need an ONNX that can accept varying input shapes at runtime, export with dynamic shapes enabled (then your runtime can feed different H×W sizes):
yolo export model=yolo26n.pt format=onnx dynamic=Truefrom ultralytics import YOLO model = YOLO("yolo26n.pt") model.export(format="onnx", dynamic=True)Feel free to drop the exact input resolutions (and whether this is video-only) here in the discussion and we can suggest a good
imgszstrategy for your case.1amani784
Thank you so much ,but for tensorRT export , the model can't accept varying input shapes and i was obliged to put imgsz or my videos have different resolutions and i can't put one imgsz value that can fit all the resolutions. Is there any other solution?
Glenn JocherUltralyticsYes—TensorRT doesn’t have to be fixed-shape: export your
.enginewithdynamic=Trueso the runtime can accept varying input shapes (you can then chooseimgszper run/video), see the Export mode docs and the TensorRT integration guide.yolo export model=yolo26n.pt format=engine dynamic=TrueIf you need peak throughput and your resolutions vary a lot, the usual workaround is exporting 2–3 fixed engines at common
imgszvalues and selecting the closest one at runtime.1
Asshok1
Hey @glenn-jocher, I’m trying to integrate a TensorRT-optimized YOLO model (.engine) with SAHI (Slicing Aided Hyper Inference) for efficient large-image inference, but I’m facing difficulties making them work together correctly as .engine is not accepted in sahi, can you help in providing the complete code for integrating tensorRT with sahi.
Glenn JocherUltralyticsSAHI’s built-in Ultralytics integration (
model_type="ultralytics") currently expects PyTorch weights like*.pt, so a TensorRT*.enginefile won’t load through SAHI as-is; the supported path is to use SAHI with*.ptper the SAHI tiled inference guide, or run the TensorRT engine directly with Ultralytics per the TensorRT export/inference guide. If you specifically need SAHI slicing + a*.engine, you’ll need a custom SAHIDetectionModeladapter around Ultralytics’ TensorRT predictor (best tracked upstream in the SAHI repository); please paste your Ultralytics/SAHI versions and a minimal repro here in the discussion so we can advise on the cleanest adapter approach.# SAHI (supported): Ultralytics *.pt + slicing from sahi import AutoDetectionModel from sahi.predict import get_sliced_prediction detection_model = AutoDetectionModel.from_pretrained( model_type="ultralytics", model_path="best.pt", confidence_threshold=0.25, device="cuda:0", ) result = get_sliced_prediction( "large.jpg", detection_model, slice_height=640, slice_width=640, overlap_height_ratio=0.2, overlap_width_ratio=0.2, )# TensorRT (supported): Ultralytics *.engine inference (no SAHI wrapper) from ultralytics import YOLO model = YOLO("best.engine") results = model.predict("large.jpg", device=0, imgsz=640)
hanchaoyuan
hello! I used the YOLO11-pose model to estimate the key points of people in the automotive production workshop. However, the model often identified vehicles, hoists and other equipment as humans and calculated the key points, resulting in a relatively high false alarm rate. My question is: How can we prevent the model from identifying other objects and reduce the false alarm rate?
Glenn JocherUltralyticsFor workshop false positives with pose models, the quickest lever is raising the prediction threshold (and optionally increasing
imgszfor better person discrimination), but the most reliable fix is fine-tuning on your own workshop data with “hard negative” images (frames with vehicles/hoists but no people) so the model learns your background; see the inference args in the predict mode docs.yolo pose predict model=yolo11n-pose.pt source=path/to/video.mp4 conf=0.6 imgsz=960If you paste your exact command, plus a couple representative frames (people + false positives) here in the discussion, we can suggest tighter settings or a training setup (and for new work, try a YOLO26 pose checkpoint as it’s generally stronger out of the box).
d5423197
Hi there,
If no boxes/masks detected by the model, what will be the output of model inference. (results = model(["image1.jpg", "image2.jpg"]) #)
I want to deal with the edge case.
max-dev-14
How to predict and show or save prediction YOLO (custom model) for video fragment?
