|
import cv2 |
|
import pandas as pd |
|
import pickle |
|
import os |
|
|
|
|
|
pickle_filename = "../pmfeed_4_3_16_bboxes_and_labels.pkl" |
|
video_filename = "../pmfeed_4_3_16.mp4" |
|
output_dir = "all_crops_pmfeed_4_3_16" |
|
|
|
|
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
|
|
with open(pickle_filename, "rb") as f: |
|
df = pickle.load(f) |
|
|
|
|
|
cap = cv2.VideoCapture(video_filename) |
|
if not cap.isOpened(): |
|
raise IOError(f"Cannot open video file {video_filename}") |
|
|
|
|
|
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) |
|
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
|
print(f"Video dimensions: {frame_width}x{frame_height}") |
|
|
|
|
|
num_rows = len(df) |
|
i = 0 |
|
frames_processed = 0 |
|
|
|
|
|
while i < num_rows: |
|
|
|
current_frame_id = int(df.iloc[i]["frame_id"]) |
|
j = i |
|
|
|
while j < num_rows and df.iloc[j]["frame_id"] == current_frame_id: |
|
j += 1 |
|
|
|
|
|
cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame_id - 1) |
|
ret, frame = cap.read() |
|
if not ret: |
|
print(f"Warning: Could not read frame {current_frame_id}") |
|
i = j |
|
continue |
|
|
|
|
|
for index in range(i, j): |
|
row = df.iloc[index] |
|
|
|
x_center = row["x"] |
|
y_center = row["y"] |
|
bbox_width = row["w"] |
|
bbox_height = row["h"] |
|
|
|
|
|
left = int((x_center - bbox_width / 2) * frame_width) |
|
top = int((y_center - bbox_height / 2) * frame_height) |
|
right = int((x_center + bbox_width / 2) * frame_width) |
|
bottom = int((y_center + bbox_height / 2) * frame_height) |
|
|
|
|
|
left = max(left, 0) |
|
top = max(top, 0) |
|
right = min(right, frame_width) |
|
bottom = min(bottom, frame_height) |
|
|
|
|
|
if right - left <= 0 or bottom - top <= 0: |
|
print(f"Warning: Invalid crop dimensions for frame {current_frame_id}, tracklet {row['tracklet_id']}") |
|
continue |
|
|
|
|
|
crop_img = frame[top:bottom, left:right] |
|
|
|
|
|
filename = f"pmfeed_4_3_16_frame_{current_frame_id}_cow_{int(row['tracklet_id'])}.jpg" |
|
output_path = os.path.join(output_dir, filename) |
|
cv2.imwrite(output_path, crop_img) |
|
print(f"Saved crop: {output_path}") |
|
|
|
frames_processed += 1 |
|
i = j |
|
|
|
|
|
cap.release() |
|
print("Cropping all frames completed.") |
|
|