fall / scripts /extract_pose.py
minhy112's picture
Upload project files excluding raw data folder
ae419ed verified
Raw
History Blame Contribute Delete
3.54 kB
from __future__ import annotations
import argparse
from pathlib import Path
import cv2
import numpy as np
from tqdm import tqdm
from ultralytics import YOLO
from common import ROOT, load_config
from dynafall.data import save_pickle
from dynafall.features import infer_label_from_path
VIDEO_EXTS = {".avi", ".mp4", ".mov", ".mkv", ".mpg", ".mpeg"}
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".bmp"}
def largest_person(result) -> np.ndarray:
if result.keypoints is None or result.boxes is None or len(result.boxes) == 0:
return np.zeros((17, 3), dtype=np.float32)
boxes = result.boxes.xyxy.detach().cpu().numpy()
areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
idx = int(np.argmax(areas))
xy = result.keypoints.xy[idx].detach().cpu().numpy()
conf = result.keypoints.conf[idx].detach().cpu().numpy()
return np.concatenate([xy, conf[:, None]], axis=1).astype(np.float32)
def extract_video(path: Path, model: YOLO, conf: float) -> np.ndarray:
cap = cv2.VideoCapture(str(path))
frames = []
ok, frame = cap.read()
while ok:
result = model.predict(frame, conf=conf, verbose=False)[0]
frames.append(largest_person(result))
ok, frame = cap.read()
cap.release()
return np.asarray(frames, dtype=np.float32)
def extract_image_dir(path: Path, model: YOLO, conf: float) -> np.ndarray:
frames = []
images = sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_EXTS)
for image_path in images:
frame = cv2.imread(str(image_path))
if frame is None:
continue
result = model.predict(frame, conf=conf, verbose=False)[0]
frames.append(largest_person(result))
return np.asarray(frames, dtype=np.float32)
def image_sequence_dirs(raw_dir: Path) -> list[Path]:
dirs = []
for path in raw_dir.rglob("*"):
if path.is_dir() and any(child.suffix.lower() in IMAGE_EXTS for child in path.iterdir()):
dirs.append(path)
return sorted(dirs)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--dataset", required=True)
ap.add_argument("--config", default="configs/default.yaml")
args = ap.parse_args()
cfg = load_config(args.config)
raw_dir = ROOT / "data/raw" / args.dataset
videos = [p for p in raw_dir.rglob("*") if p.suffix.lower() in VIDEO_EXTS]
image_dirs = image_sequence_dirs(raw_dir) if not videos else []
if not videos and not image_dirs:
raise SystemExit(f"No videos or image sequence directories found under {raw_dir}")
model = YOLO(cfg["pose_model"])
records = []
for path in tqdm(videos, desc=f"Extracting videos {args.dataset}"):
records.append({
"video_id": path.relative_to(raw_dir).with_suffix("").as_posix(),
"path": str(path),
"label": infer_label_from_path(str(path.relative_to(raw_dir))),
"keypoints": extract_video(path, model, cfg["conf_threshold"]),
})
for path in tqdm(image_dirs, desc=f"Extracting image dirs {args.dataset}"):
records.append({
"video_id": path.relative_to(raw_dir).as_posix(),
"path": str(path),
"label": infer_label_from_path(str(path.relative_to(raw_dir))),
"keypoints": extract_image_dir(path, model, cfg["conf_threshold"]),
})
out = ROOT / "data/poses" / f"{args.dataset}_keypoints.pkl"
save_pickle(records, out)
print(f"Wrote {out} ({len(records)} videos)")
if __name__ == "__main__":
main()