Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- apply_mask.py +72 -0
- compose_video.py +56 -0
- extract_frames.py +59 -0
- run_gmm.py +31 -0
apply_mask.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import os
|
| 3 |
+
import glob
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
def apply_mask_and_crop(input_folder, mask_path, output_folder):
|
| 7 |
+
"""
|
| 8 |
+
Apply binary mask to all images, crop to masked region, and save to output folder
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
input_folder (str): Path to folder containing input images
|
| 12 |
+
mask_path (str): Path to binary mask image
|
| 13 |
+
output_folder (str): Path to save cropped masked images
|
| 14 |
+
"""
|
| 15 |
+
# Load and prepare mask
|
| 16 |
+
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
|
| 17 |
+
if mask is None:
|
| 18 |
+
raise ValueError(f"Could not load mask from {mask_path}")
|
| 19 |
+
|
| 20 |
+
_, binary_mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
|
| 21 |
+
|
| 22 |
+
# Create output directory if it doesn't exist
|
| 23 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 24 |
+
|
| 25 |
+
# Get list of image files
|
| 26 |
+
image_files = glob.glob(os.path.join(input_folder, "*.jpg")) + \
|
| 27 |
+
glob.glob(os.path.join(input_folder, "*.png")) + \
|
| 28 |
+
glob.glob(os.path.join(input_folder, "*.bmp"))
|
| 29 |
+
|
| 30 |
+
if not image_files:
|
| 31 |
+
print(f"No images found in {input_folder}")
|
| 32 |
+
return
|
| 33 |
+
|
| 34 |
+
print(f"Found {len(image_files)} images to process")
|
| 35 |
+
|
| 36 |
+
for img_path in image_files:
|
| 37 |
+
# Load image
|
| 38 |
+
img = cv2.imread(img_path)
|
| 39 |
+
if img is None:
|
| 40 |
+
print(f"Warning: Could not read image {img_path}")
|
| 41 |
+
continue
|
| 42 |
+
|
| 43 |
+
# Resize mask if dimensions don't match
|
| 44 |
+
if img.shape[:2] != binary_mask.shape[:2]:
|
| 45 |
+
resized_mask = cv2.resize(binary_mask, (img.shape[1], img.shape[0]))
|
| 46 |
+
else:
|
| 47 |
+
resized_mask = binary_mask
|
| 48 |
+
|
| 49 |
+
# Apply mask
|
| 50 |
+
masked_img = cv2.bitwise_and(img, img, mask=resized_mask)
|
| 51 |
+
|
| 52 |
+
# Find contours to get bounding box of mask
|
| 53 |
+
contours, _ = cv2.findContours(resized_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 54 |
+
if not contours:
|
| 55 |
+
print(f"No mask area found in {img_path} - skipping")
|
| 56 |
+
continue
|
| 57 |
+
|
| 58 |
+
# Get bounding rectangle of largest contour
|
| 59 |
+
x, y, w, h = cv2.boundingRect(max(contours, key=cv2.contourArea))
|
| 60 |
+
|
| 61 |
+
# Crop to masked region
|
| 62 |
+
cropped_img = masked_img[y:y+h, x:x+w]
|
| 63 |
+
|
| 64 |
+
# Create output path (preserve original filename)
|
| 65 |
+
filename = os.path.basename(img_path)
|
| 66 |
+
output_path = os.path.join(output_folder, filename)
|
| 67 |
+
|
| 68 |
+
# Save cropped image
|
| 69 |
+
cv2.imwrite(output_path, cropped_img)
|
| 70 |
+
# print(f"Processed and saved: {output_path}")
|
| 71 |
+
|
| 72 |
+
print(f"\nProcessing complete! Saved {len(image_files)} cropped images to {output_folder}")
|
compose_video.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
def compose_final_video(mask_path, frames_folder, extracted_frames_folder, output_path, fps=24):
|
| 6 |
+
"""
|
| 7 |
+
Composes the final heatmap video by placing each heatmap frame
|
| 8 |
+
on top of its corresponding original frame using the table region defined by the mask.
|
| 9 |
+
"""
|
| 10 |
+
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
|
| 11 |
+
if mask is None:
|
| 12 |
+
raise ValueError(f"Mask not found at {mask_path}")
|
| 13 |
+
|
| 14 |
+
_, binary_mask = cv2.threshold(mask, 200, 255, cv2.THRESH_BINARY)
|
| 15 |
+
height, width = binary_mask.shape
|
| 16 |
+
|
| 17 |
+
contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 18 |
+
if not contours:
|
| 19 |
+
raise ValueError("No white area found in mask")
|
| 20 |
+
|
| 21 |
+
table_contour = max(contours, key=cv2.contourArea)
|
| 22 |
+
x, y, w, h = cv2.boundingRect(table_contour)
|
| 23 |
+
|
| 24 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 25 |
+
video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
|
| 26 |
+
|
| 27 |
+
heatmap_files = sorted([f for f in os.listdir(frames_folder) if f.endswith(('.bmp', '.jpg', '.png'))])
|
| 28 |
+
original_files = sorted([f for f in os.listdir(extracted_frames_folder) if f.endswith(('.bmp', '.jpg', '.png'))])
|
| 29 |
+
|
| 30 |
+
if len(heatmap_files) != len(original_files):
|
| 31 |
+
raise ValueError("Mismatch between number of heatmap frames and original frames")
|
| 32 |
+
|
| 33 |
+
for heatmap_file, original_file in zip(heatmap_files, original_files):
|
| 34 |
+
heatmap = cv2.imread(os.path.join(frames_folder, heatmap_file))
|
| 35 |
+
original = cv2.imread(os.path.join(extracted_frames_folder, original_file))
|
| 36 |
+
|
| 37 |
+
if heatmap is None or original is None:
|
| 38 |
+
continue
|
| 39 |
+
|
| 40 |
+
ph, pw = heatmap.shape[:2]
|
| 41 |
+
if pw > w or ph > h:
|
| 42 |
+
scale = min(w / pw, h / ph)
|
| 43 |
+
heatmap = cv2.resize(heatmap, (int(pw * scale), int(ph * scale)))
|
| 44 |
+
pw, ph = heatmap.shape[1], heatmap.shape[0]
|
| 45 |
+
|
| 46 |
+
x_offset = x + (w - pw) // 2
|
| 47 |
+
y_offset = y + (h - ph) // 2
|
| 48 |
+
|
| 49 |
+
result = original.copy()
|
| 50 |
+
result[y_offset:y_offset+ph, x_offset:x_offset+pw] = heatmap
|
| 51 |
+
cv2.drawContours(result, [table_contour], -1, (0, 255, 0), 2)
|
| 52 |
+
|
| 53 |
+
video_writer.write(result)
|
| 54 |
+
|
| 55 |
+
video_writer.release()
|
| 56 |
+
print("[Video] Final video saved to:", output_path)
|
extract_frames.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
def video_to_keyframes(video_path, output_folder, frame_interval=1, prefix='frame'):
|
| 5 |
+
"""
|
| 6 |
+
Convert video to keyframes (individual frames) and save as images
|
| 7 |
+
|
| 8 |
+
Args:
|
| 9 |
+
video_path (str): Path to input video file
|
| 10 |
+
output_folder (str): Directory to save extracted frames
|
| 11 |
+
frame_interval (int): Extract every nth frame (1=every frame)
|
| 12 |
+
prefix (str): Prefix for saved frame files
|
| 13 |
+
"""
|
| 14 |
+
# Create output directory if it doesn't exist
|
| 15 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# Open the video file
|
| 18 |
+
cap = cv2.VideoCapture(video_path)
|
| 19 |
+
if not cap.isOpened():
|
| 20 |
+
raise ValueError(f"Could not open video {video_path}")
|
| 21 |
+
|
| 22 |
+
# Get video properties
|
| 23 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 24 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 25 |
+
duration = total_frames / fps
|
| 26 |
+
|
| 27 |
+
print(f"Video Info:")
|
| 28 |
+
print(f"- Path: {video_path}")
|
| 29 |
+
print(f"- FPS: {fps}")
|
| 30 |
+
print(f"- Total Frames: {total_frames}")
|
| 31 |
+
print(f"- Duration: {duration:.2f} seconds")
|
| 32 |
+
print(f"- Extracting every {frame_interval} frame(s)")
|
| 33 |
+
|
| 34 |
+
frame_count = 0
|
| 35 |
+
saved_count = 0
|
| 36 |
+
|
| 37 |
+
while True:
|
| 38 |
+
ret, frame = cap.read()
|
| 39 |
+
|
| 40 |
+
# Stop if we've reached the end of the video
|
| 41 |
+
if not ret:
|
| 42 |
+
break
|
| 43 |
+
|
| 44 |
+
# Only process frames at the specified interval
|
| 45 |
+
if frame_count % frame_interval == 0:
|
| 46 |
+
# Save frame as image file
|
| 47 |
+
frame_filename = f"{prefix}_{saved_count:06d}.jpg"
|
| 48 |
+
output_path = os.path.join(output_folder, frame_filename)
|
| 49 |
+
cv2.imwrite(output_path, frame)
|
| 50 |
+
saved_count += 1
|
| 51 |
+
|
| 52 |
+
# Print progress every 100 frames
|
| 53 |
+
if saved_count % 100 == 0:
|
| 54 |
+
print(f"Saved frame {saved_count} (original frame {frame_count})")
|
| 55 |
+
|
| 56 |
+
frame_count += 1
|
| 57 |
+
|
| 58 |
+
# Release resources
|
| 59 |
+
cap.release()
|
run_gmm.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import glob
|
| 4 |
+
from GMM import GMM
|
| 5 |
+
|
| 6 |
+
def run_gmm_inference(input_dir, output_dir):
|
| 7 |
+
"""
|
| 8 |
+
Applies GMM model inference on all frames in input_dir,
|
| 9 |
+
saves results with heatmap overlays to output_dir.
|
| 10 |
+
"""
|
| 11 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 12 |
+
test_files = sorted(glob.glob(os.path.join(input_dir, '*.jpg')))
|
| 13 |
+
|
| 14 |
+
if not test_files:
|
| 15 |
+
raise ValueError("No input images found for GMM inference.")
|
| 16 |
+
|
| 17 |
+
heatmap = None
|
| 18 |
+
gmm = GMM.load_model("gmm_model.joblib")
|
| 19 |
+
|
| 20 |
+
for index, file in enumerate(test_files):
|
| 21 |
+
# print(f"[GMM] Processing: {file}")
|
| 22 |
+
img = cv2.imread(file)
|
| 23 |
+
if img is None:
|
| 24 |
+
print(f"Warning: Skipped unreadable file {file}")
|
| 25 |
+
continue
|
| 26 |
+
|
| 27 |
+
result_img, heatmap = gmm.infer(img, heatmap)
|
| 28 |
+
output_path = os.path.join(output_dir, f"{index:05d}.bmp")
|
| 29 |
+
cv2.imwrite(output_path, result_img)
|
| 30 |
+
|
| 31 |
+
print("[GMM] Inference complete. Output saved to:", output_dir)
|