📑
YOLOv8を使ったボール検出と座標取得
執筆日
2026/1/30
やること
YOLOv8(Ultralytics)を用いて画像内のボール(sports ball)の座標を取得する
使う画像

ライブラリをインストール
pip install ultralytics opencv-python
code
main.py
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
results = model("画像のパス", conf=0.25)
r = results[0]
boxes = r.boxes
xyxy = boxes.xyxy.cpu().numpy()
xywh = boxes.xywh.cpu().numpy()
xyxyn = boxes.xyxyn.cpu().numpy()
xywhn = boxes.xywhn.cpu().numpy()
cls = boxes.cls.cpu().numpy().astype(int)
conf = boxes.conf.cpu().numpy()
for i in range(len(xyxy)):
x1, y1, x2, y2 = xyxy[i]
print({
"class_id": int(cls[i]),
"conf": float(conf[i]),
"xyxy": [float(x1), float(y1), float(x2), float(y2)],
"xywh": [float(v) for v in xywh[i]],
})
出力結果
Speed: 2.6ms preprocess, 57.1ms inference, 1.4ms postprocess per image at shape (1, 3, 384, 640)
{'class_id': 33, 'conf': 0.3861016035079956, 'xyxy': [341.64447021484375, 116.98239135742188, 742.3426513671875, 483.0838623046875], 'xywh': [541.9935302734375, 300.03314208984375, 400.69818115234375, 366.1014709472656]}
Discussion