Ultralytics
Ultralytics YOLO 활용 실습
COCO Dataset
- COCO (Common Objects in Context)
- 대규모 물체 탐지, 세그멘테이션, 캡셔닝 데이터셋
- 서브셋:
- Train2017: 훈련용 118K 이미지
- Val2017: 검증용 5K 이미지
- Test2017: 테스트용 20K 이미지
- 80개 사물 카테고리: 자동차, 자전거, 동물 등
모델 종류
- COCO 데이터셋에 사전 학습
- 모든 모델은 640x640 크기의 이미지를 입력으로 받음
- 크기가 다를 경우 자동으로 리사이즈
- n → s → m → l → x 순으로 커짐
- 작을 수록 빠르고, 클 수록 성능이 높음
사전 학습된 모델을 이용한 물체 탐지
from ultralytics import YOLO
model = YOLO("yolo11n.pt")
results = model('bus_stop.jpg')
import cv2 as cv
img = cv.imread("bus_stop.jpg")
results = model(img)
results = model(img, conf=0.8)
결과 출력
for r in results:
print(r.boxes.xyxy)
print(r.boxes.cls)
print(r.boxes.conf)
결과 시각화
from PIL import Image, ImageDraw, ImageFont
try:
font = ImageFont.truetype("NanumGothic.ttf", 20)
except IOError:
font = ImageFont.load_default()
img_bbox = Image.fromarray(cv.cvtColor(img, cv.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img_bbox)
result = results[0]
boxes = result.boxes
for i, box in enumerate(boxes):
xyxy = box.xyxy[0].cpu().numpy()
cls_id = int(box.cls[0].cpu().numpy())
confidence = float(box.conf[0].cpu().numpy())
x1, y1, x2, y2 = xyxy.astype(int)
draw.rectangle([x1, y1, x2, y2], outline="#00FF00", width=3)
label = f"{result.names[cls_id]}({confidence:.2f})"
draw.text((x1, y1), label, fill="#00FF00", font=font)
img_bbox