fabriquedoc-backend/convert_video.py
2024-11-11 01:11:33 -05:00

76 lines
No EOL
2.9 KiB
Python

import logging
import os
import cv2
def convert_video(images_path, output_path, width, height, fps, stilltime):
"""
Convert images in output_path into a mp4 file using OpenCV.
:param images_path: Path to the directory containing input images
:param output_path: Path for the output video file
:param width: Width of the output video
:param height: Height of the output video
:param fps: Frames per second for the output video
:param stilltime: Duration (in seconds) each image should be displayed
:return: True if conversion was successful, False otherwise
"""
logging.info(f"Starting video conversion. OpenCV version: {cv2.__version__}")
logging.info(f"Parameters: images_path={images_path}, output_path={output_path}, width={width}, height={height}, fps={fps}, stilltime={stilltime}")
# Check if the output directory exists
output_dir = os.path.dirname(output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
logging.info(f"Created output directory: {output_dir}")
# Define a frame array
frame_array = []
# List all files in images_path
files = [f for f in os.listdir(images_path) if os.path.isfile(os.path.join(images_path, f))]
files.sort()
logging.info(f"Found {len(files)} files in {images_path}")
# Read and process images
for i, file in enumerate(files):
file_path = os.path.join(images_path, file)
logging.info(f'Processing image {i+1}/{len(files)}: {file_path}')
img = cv2.imread(file_path)
if img is None:
logging.error(f"Failed to read image: {file_path}")
continue
if img.shape[:2] != (height, width):
logging.info(f"Resizing image from {img.shape[:2]} to {(height, width)}")
img = cv2.resize(img, (width, height))
for _ in range(int(fps * stilltime)):
frame_array.append(img)
logging.info(f"Total frames to write: {len(frame_array)}")
# Create video writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
if not video_writer.isOpened():
logging.error(f"Failed to open VideoWriter for {output_path}")
return False
# Write frames
for i, frame in enumerate(frame_array):
video_writer.write(frame)
if i % 100 == 0:
logging.info(f"Wrote frame {i+1}/{len(frame_array)}")
video_writer.release()
# Verify output
if os.path.exists(output_path):
file_size = os.path.getsize(output_path)
logging.info(f'Finished converting. Output file: {output_path}, Size: {file_size} bytes')
if file_size > 1000:
return True
else:
logging.warning(f"Output file is suspiciously small: {file_size} bytes")
else:
logging.error(f"Output file was not created: {output_path}")
return False