Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 50 additions & 16 deletions core/frame_to_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,41 @@
import json
import os
from datetime import datetime
from os.path import isfile, join

import cv2
import numpy as np

# Initialize parser
parser = argparse.ArgumentParser()

# Adding optional argument
parser.add_argument("-n", "--name", help="name of video")

# Load the frame data from JSON
frame_data = open("./frameCreationInfo.json")
frame_data = json.load(frame_data)


def convert_frames_to_video(pathIn, pathOut, fps):
def convert_frames_to_video(pathIn, pathOut, fps, frame_data, cv2_module=cv2):
"""
Optimized OpenCV method with better codec and settings
"""
try:
# Load the first image to get video dimensions
first_frame_key = frame_data["frame_key"]["0"]
frame_keys = frame_data.get("frame_key")
if not frame_keys:
print("Error: Metadata is missing frame_key entries.")
return False

first_frame_key = frame_keys.get("0") if isinstance(frame_keys, dict) else None
if first_frame_key is None:
print("Error: Metadata does not contain a first frame entry.")
return False

first_frame_path = pathIn + first_frame_key + ".png"
Copy link

Copilot AI Oct 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using string concatenation for file paths can cause issues on different operating systems. Use os.path.join(pathIn, first_frame_key + '.png') instead for cross-platform compatibility.

Copilot uses AI. Check for mistakes.
img = cv2.imread(first_frame_path)

if not os.path.exists(first_frame_path):
print(
"Error: First frame not found at"
f" {first_frame_path}. Please ensure frames are generated."
Comment on lines +34 to +35
Copy link

Copilot AI Oct 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message spans two lines with incorrect string concatenation. The space should be included in the f-string to avoid 'Error: First frame not found at{path}' output.

Suggested change
"Error: First frame not found at"
f" {first_frame_path}. Please ensure frames are generated."
f"Error: First frame not found at {first_frame_path}. Please ensure frames are generated."

Copilot uses AI. Check for mistakes.
)
return False

img = cv2_module.imread(first_frame_path)

if img is None:
print(f"Error: Unable to read the image {first_frame_path}")
Expand All @@ -36,20 +46,32 @@ def convert_frames_to_video(pathIn, pathOut, fps):
size = (width, height)

# Use H.264 codec for better compression and quality
fourcc = cv2.VideoWriter_fourcc(*"mp4v") # or 'H264' if available
out = cv2.VideoWriter(pathOut, fourcc, fps, size)
fourcc = cv2_module.VideoWriter_fourcc(*"mp4v") # or 'H264' if available
out = cv2_module.VideoWriter(pathOut, fourcc, fps, size)

if not out.isOpened():
print("Error: VideoWriter could not be opened")
return False

# Process frames in order using frame_data
total_frames = len(frame_data["frame_key"])
total_frames = len(frame_keys)
print(f"Creating video with {total_frames} frames...")

for counter in range(total_frames):
filename = pathIn + frame_data["frame_key"][str(counter)] + ".png"
img = cv2.imread(filename)
try:
frame_key = (
frame_keys[str(counter)]
if isinstance(frame_keys, dict)
else frame_keys[counter]
)
except (KeyError, IndexError):
print(
f"Warning: Metadata missing frame entry for index {counter}, skipping frame."
)
continue

filename = pathIn + frame_key + ".png"
Copy link

Copilot AI Oct 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using string concatenation for file paths can cause issues on different operating systems. Use os.path.join(pathIn, frame_key + '.png') instead for cross-platform compatibility.

Copilot uses AI. Check for mistakes.
img = cv2_module.imread(filename)

if img is None:
print(f"Error: Unable to read the image {filename}")
Expand Down Expand Up @@ -88,11 +110,23 @@ def main():

print(f"Creating video with file name: {name}")

metadata_path = "./frameCreationInfo.json"

if not os.path.exists(metadata_path):
print(
"Error: Metadata file frameCreationInfo.json not found. "
"Please run the frame generator before creating a video."
)
return

with open(metadata_path) as metadata_file:
frame_data = json.load(metadata_file)

# Set frames per second (FPS) for the video
fps = 24.0

# Convert the frames to a video
convert_frames_to_video(pathIn, pathOut, fps)
convert_frames_to_video(pathIn, pathOut, fps, frame_data)


if __name__ == "__main__":
Expand Down