-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_sam2_video_predict.py
More file actions
80 lines (66 loc) · 1.75 KB
/
Copy path3_sam2_video_predict.py
File metadata and controls
80 lines (66 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import numpy as np
import torch
from sam2.build_sam import build_sam2_video_predictor
# PATHS
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
VIDEO_PATH = os.path.join(
BASE_DIR,
"..",
"Preprocessing_Training",
"output1",
"Idisc001_video.mp4"
)
OUTPUT_MASK_DIR = os.path.join(
BASE_DIR,
"..",
"Preprocessing_Training",
"sam2_outputs"
)
os.makedirs(OUTPUT_MASK_DIR, exist_ok=True)
# SAM2 CONFIG AND CHECKPOINT
CONFIG_NAME = "configs/sam2.1/sam2.1_hiera_t.yaml"
CHECKPOINT_PATH = os.path.join(
BASE_DIR,
"..",
"SAM2",
"checkpoints",
"sam2.1_hiera_tiny.pt"
)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# LOAD SAM2 VIDEO PREDICTOR
predictor = build_sam2_video_predictor(
config_file=CONFIG_NAME,
ckpt_path=CHECKPOINT_PATH,
device=DEVICE,
)
print("SAM2 video predictor loaded successfully")
# INIT INFERENCE STATE WITH VIDEO PATH
inference_state = predictor.init_state(VIDEO_PATH)
print("Video loaded and inference state initialized")
# SINGLE-POINT PROMPT (LSO)
# Add center click on first frame
frame_idx = 0
obj_id = 1
point = np.array([[0, 0]]) # placeholder, will be interpreted by predictor
label = np.array([1]) # foreground
predictor.add_new_points(
inference_state=inference_state,
frame_idx=frame_idx,
obj_id=obj_id,
points=point,
labels=label
)
# RUN VIDEO PROPAGATION
for frame_idx, obj_ids, masks in predictor.propagate_in_video(inference_state):
mask = masks[0].cpu().numpy()
mask = (mask > 0).astype(np.uint8)
np.save(
os.path.join(
OUTPUT_MASK_DIR,
f"frame_{frame_idx:04d}.npy"
),
mask
)
print(f"Saved mask for frame {frame_idx}")
print(" video segmentation COMPLETED")