Upload files to "/"
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
"""
|
||||
YOLO26 - 8 Computer Vision Tasks on a Single Video
|
||||
----------------------------------------------------
|
||||
Video used for ALL tasks: ai_video.mp4 (must be in the same folder as this script)
|
||||
|
||||
Tasks:
|
||||
1. Detection -> annotated output video
|
||||
2. Tracking -> REAL tracking now (IDs persist across frames)
|
||||
3. Segmentation -> annotated output video
|
||||
4. Pose estimation -> SKIPPED here (no person expected in ai_video, code kept but commented out)
|
||||
5. Classification (per-frame top-1 label overlay, see accuracy note below)
|
||||
6. ROI extraction (crops each detected box out of SAMPLED frames)
|
||||
7. Depth estimation (native YOLO26 task, yolo26n-depth.pt) -> colorized depth video
|
||||
8. OBB -> SKIPPED here (DOTA aerial classes don't match everyday scenes), commented out
|
||||
|
||||
All results are saved into ./results/
|
||||
|
||||
Install:
|
||||
pip install -U ultralytics
|
||||
"""
|
||||
|
||||
import os
|
||||
import cv2
|
||||
import numpy as np
|
||||
from ultralytics import YOLO
|
||||
|
||||
VIDEO_PATH = "ai_video.mp4"
|
||||
OUT_DIR = "results"
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
|
||||
# How often (in frames) to save ROI crops / raw depth npy files.
|
||||
# Video = many frames, so we sample instead of dumping one file per box per frame.
|
||||
ROI_FRAME_STRIDE = 15 # save ROI crops every 15th frame
|
||||
DEPTH_NPY_STRIDE = 30 # save raw depth .npy every 30th frame
|
||||
|
||||
|
||||
def open_writer(path, fps, w, h):
|
||||
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
||||
return cv2.VideoWriter(path, fourcc, fps, (w, h))
|
||||
|
||||
|
||||
def get_video_props(video_path):
|
||||
cap = cv2.VideoCapture(video_path)
|
||||
if not cap.isOpened():
|
||||
raise FileNotFoundError(f"Could not open '{video_path}'.")
|
||||
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
|
||||
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
cap.release()
|
||||
return fps, w, h, n_frames
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
if not os.path.exists(VIDEO_PATH):
|
||||
raise FileNotFoundError(f"'{VIDEO_PATH}' not found in current folder.")
|
||||
|
||||
fps, W, H, N_FRAMES = get_video_props(VIDEO_PATH)
|
||||
print(f"Video: {VIDEO_PATH} | {W}x{H} @ {fps:.2f}fps | ~{N_FRAMES} frames")
|
||||
|
||||
# ==========================================================
|
||||
# 1) DETECTION
|
||||
# ==========================================================
|
||||
det_boxes_by_frame = {} # kept for ROI extraction (task 6) later
|
||||
try:
|
||||
det_model = YOLO("yolo26n.pt")
|
||||
writer = open_writer(os.path.join(OUT_DIR, "1_detection.mp4"), fps, W, H)
|
||||
|
||||
for frame_idx, result in enumerate(det_model(VIDEO_PATH, stream=True)):
|
||||
writer.write(result.plot())
|
||||
det_boxes_by_frame[frame_idx] = result
|
||||
|
||||
writer.release()
|
||||
print(f"[1 - Detection] Saved: {os.path.join(OUT_DIR, '1_detection.mp4')}")
|
||||
except Exception as e:
|
||||
print(f"[1 - Detection] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 2) TRACKING
|
||||
# NOTE: unlike the single-image version, this is now REAL tracking -
|
||||
# object IDs persist across frames using motion + appearance, since
|
||||
# a video actually has a time dimension to track across.
|
||||
# ==========================================================
|
||||
try:
|
||||
track_model = YOLO("yolo26n.pt")
|
||||
writer = open_writer(os.path.join(OUT_DIR, "2_tracking.mp4"), fps, W, H)
|
||||
|
||||
# stream=True + persist=True keeps track IDs consistent frame-to-frame
|
||||
for result in track_model.track(VIDEO_PATH, persist=True, stream=True):
|
||||
writer.write(result.plot())
|
||||
|
||||
writer.release()
|
||||
print(f"[2 - Tracking] Saved: {os.path.join(OUT_DIR, '2_tracking.mp4')}")
|
||||
except Exception as e:
|
||||
print(f"[2 - Tracking] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 3) SEGMENTATION
|
||||
# ==========================================================
|
||||
try:
|
||||
seg_model = YOLO("yolo26n-seg.pt")
|
||||
writer = open_writer(os.path.join(OUT_DIR, "3_segmentation.mp4"), fps, W, H)
|
||||
|
||||
for result in seg_model(VIDEO_PATH, stream=True):
|
||||
writer.write(result.plot())
|
||||
|
||||
writer.release()
|
||||
print(f"[3 - Segmentation] Saved: {os.path.join(OUT_DIR, '3_segmentation.mp4')}")
|
||||
except Exception as e:
|
||||
print(f"[3 - Segmentation] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 4) POSE ESTIMATION - SKIPPED
|
||||
# Pose models detect HUMAN keypoints (COCO-pose, 17 points/person).
|
||||
# If ai_video.mp4 has no person in frame, this returns empty results
|
||||
# for every frame. Uncomment and point at footage containing a
|
||||
# person to use it.
|
||||
# ==========================================================
|
||||
# try:
|
||||
# pose_model = YOLO("yolo26n-pose.pt")
|
||||
# writer = open_writer(os.path.join(OUT_DIR, "4_pose.mp4"), fps, W, H)
|
||||
# for result in pose_model(VIDEO_PATH, stream=True):
|
||||
# writer.write(result.plot())
|
||||
# writer.release()
|
||||
# print(f"[4 - Pose] Saved: {os.path.join(OUT_DIR, '4_pose.mp4')}")
|
||||
# except Exception as e:
|
||||
# print(f"[4 - Pose] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 5) CLASSIFICATION
|
||||
# NOTE: classification models expect ONE dominant subject per frame
|
||||
# (ImageNet-style). If frames have many objects side by side, the
|
||||
# top-1 prediction is just whatever looks most salient to the model
|
||||
# per frame - treat it as a rough per-frame guess, not a scene
|
||||
# description or a stable video-level label.
|
||||
# ==========================================================
|
||||
try:
|
||||
cls_model = YOLO("yolo26n-cls.pt")
|
||||
writer = open_writer(os.path.join(OUT_DIR, "5_classification.mp4"), fps, W, H)
|
||||
cls_log = []
|
||||
|
||||
for frame_idx, result in enumerate(cls_model(VIDEO_PATH, stream=True)):
|
||||
writer.write(result.plot())
|
||||
top1_idx = int(result.probs.top1)
|
||||
top1_conf = float(result.probs.top1conf)
|
||||
cls_log.append((frame_idx, result.names[top1_idx], round(top1_conf, 3)))
|
||||
|
||||
writer.release()
|
||||
print(f"[5 - Classification] Saved: {os.path.join(OUT_DIR, '5_classification.mp4')}")
|
||||
print(f"[5 - Classification] First 5 frame guesses: {cls_log[:5]}")
|
||||
|
||||
with open(os.path.join(OUT_DIR, "5_classification_log.txt"), "w") as f:
|
||||
for frame_idx, label, conf in cls_log:
|
||||
f.write(f"frame {frame_idx}: {label} ({conf})\n")
|
||||
except Exception as e:
|
||||
print(f"[5 - Classification] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 6) ROI EXTRACTION
|
||||
# Not a separate YOLO model - "ROI" here means cropping each detected
|
||||
# bounding box out of the original frame and saving it as its own file.
|
||||
# Reuses the detection results from Task 1, but only every
|
||||
# ROI_FRAME_STRIDE-th frame (a full video would otherwise produce
|
||||
# thousands of crop files).
|
||||
# ==========================================================
|
||||
try:
|
||||
if det_boxes_by_frame:
|
||||
cap = cv2.VideoCapture(VIDEO_PATH)
|
||||
roi_dir = os.path.join(OUT_DIR, "6_roi_crops")
|
||||
os.makedirs(roi_dir, exist_ok=True)
|
||||
total_crops = 0
|
||||
|
||||
frame_idx = 0
|
||||
while True:
|
||||
ret, frame = cap.read()
|
||||
if not ret:
|
||||
break
|
||||
|
||||
if frame_idx % ROI_FRAME_STRIDE == 0 and frame_idx in det_boxes_by_frame:
|
||||
result = det_boxes_by_frame[frame_idx]
|
||||
for i, box in enumerate(result.boxes):
|
||||
x1, y1, x2, y2 = map(int, box.xyxy[0])
|
||||
crop = frame[max(y1, 0):y2, max(x1, 0):x2]
|
||||
if crop.size == 0:
|
||||
continue
|
||||
label = result.names[int(box.cls[0])]
|
||||
fname = f"frame{frame_idx}_roi{i}_{label}.png"
|
||||
cv2.imwrite(os.path.join(roi_dir, fname), crop)
|
||||
total_crops += 1
|
||||
|
||||
frame_idx += 1
|
||||
|
||||
cap.release()
|
||||
print(f"[6 - ROI] Saved {total_crops} crops (every {ROI_FRAME_STRIDE} frames) to {roi_dir}")
|
||||
else:
|
||||
print("[6 - ROI] Skipped: no detection results available.")
|
||||
except Exception as e:
|
||||
print(f"[6 - ROI] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 7) DEPTH ESTIMATION
|
||||
# Native YOLO26 task - yolo26n-depth.pt outputs a per-pixel metric
|
||||
# depth map (meters) per frame. Saved as a colorized depth video;
|
||||
# raw .npy depth arrays are saved only every DEPTH_NPY_STRIDE frames
|
||||
# to keep disk usage reasonable.
|
||||
# ==========================================================
|
||||
try:
|
||||
depth_model = YOLO("yolo26n-depth.pt")
|
||||
writer = open_writer(os.path.join(OUT_DIR, "7_depth.mp4"), fps, W, H)
|
||||
depth_npy_dir = os.path.join(OUT_DIR, "7_depth_raw")
|
||||
os.makedirs(depth_npy_dir, exist_ok=True)
|
||||
|
||||
min_d, max_d = None, None
|
||||
for frame_idx, result in enumerate(depth_model(VIDEO_PATH, stream=True, imgsz=768)):
|
||||
depth_map = result.depth.data.cpu().numpy() # (H, W) float32, meters
|
||||
|
||||
if frame_idx % DEPTH_NPY_STRIDE == 0:
|
||||
np.save(os.path.join(depth_npy_dir, f"frame{frame_idx}.npy"), depth_map)
|
||||
|
||||
d_min, d_max = float(depth_map.min()), float(depth_map.max())
|
||||
min_d = d_min if min_d is None else min(min_d, d_min)
|
||||
max_d = d_max if max_d is None else max(max_d, d_max)
|
||||
|
||||
depth_norm = cv2.normalize(depth_map, None, 0, 255, cv2.NORM_MINMAX).astype("uint8")
|
||||
depth_color = cv2.applyColorMap(depth_norm, cv2.COLORMAP_MAGMA)
|
||||
depth_color = cv2.resize(depth_color, (W, H))
|
||||
writer.write(depth_color)
|
||||
|
||||
writer.release()
|
||||
print(f"[7 - Depth] Saved depth video. Range across clip: {min_d:.2f}m - {max_d:.2f}m")
|
||||
print(f"[7 - Depth] Raw depth arrays (every {DEPTH_NPY_STRIDE} frames) saved to {depth_npy_dir}")
|
||||
except Exception as e:
|
||||
print(f"[7 - Depth] FAILED: {e}")
|
||||
|
||||
# ==========================================================
|
||||
# 8) OBB - SKIPPED
|
||||
# OBB models (yolo26n-obb.pt) are trained on DOTA (aerial/satellite
|
||||
# imagery - planes, ships, vehicles, storage tanks, etc.). Unless
|
||||
# ai_video.mp4 is aerial/satellite footage, this would return zero
|
||||
# detections. Uncomment and point at aerial video to use it.
|
||||
# ==========================================================
|
||||
# try:
|
||||
# obb_model = YOLO("yolo26n-obb.pt")
|
||||
# writer = open_writer(os.path.join(OUT_DIR, "8_obb.mp4"), fps, W, H)
|
||||
# for result in obb_model(VIDEO_PATH, stream=True):
|
||||
# writer.write(result.plot())
|
||||
# writer.release()
|
||||
# print(f"[8 - OBB] Saved: {os.path.join(OUT_DIR, '8_obb.mp4')}")
|
||||
# except Exception as e:
|
||||
# print(f"[8 - OBB] FAILED: {e}")
|
||||
|
||||
print("\nDone. Check the 'results' folder for all saved outputs.")
|
||||
Reference in New Issue
Block a user