{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Create Video!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pip install opencv-python opencv-python-headless # If you do not need GUI features\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating the demo\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import subprocess\n", "import logging\n", "from glob import glob\n", "import re\n", "\n", "# Configure logging\n", "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n", "logger = logging.getLogger(__name__)\n", "\n", "def create_near_lossless_h265_video(input_folder, output_file, fps=30, frames_per_image=3, crf=10):\n", " if not os.path.exists(input_folder):\n", " logger.error(f\"Input folder '{input_folder}' does not exist.\")\n", " return\n", "\n", " png_files = sorted(glob(os.path.join(input_folder, '*.png')))\n", " if not png_files:\n", " logger.error(f\"No PNG files found in {input_folder}\")\n", " return\n", "\n", " num_images = len(png_files)\n", " logger.info(f\"Found {num_images} PNG files.\")\n", "\n", " # Calculate expected duration\n", " expected_duration = (num_images * frames_per_image) / fps\n", " logger.info(f\"Expected duration: {expected_duration:.2f} seconds\")\n", "\n", " # FFmpeg command for near-lossless 10-bit H.265 encoding\n", " ffmpeg_command = [\n", " 'ffmpeg',\n", " '-framerate', f'{1/(frames_per_image/fps)}', # Input framerate\n", " '-i', os.path.join(input_folder, '%*.png'), # Input pattern for all PNG files\n", " '-fps_mode', 'vfr',\n", " '-pix_fmt', 'yuv420p10le', # 10-bit pixel format\n", " '-c:v', 'libx265', # Use libx265 encoder\n", " '-preset', 'slow', # Slowest preset for best compression efficiency\n", " '-crf', str(crf), # Constant Rate Factor (0-51, lower is higher quality)\n", " '-profile:v', 'main10', # 10-bit profile\n", " '-x265-params', f\"log-level=error:keyint={2*fps}:min-keyint={fps}:scenecut=0\", # Ensure consistent encoding\n", " '-tag:v', 'hvc1',\n", " '-y',\n", " output_file\n", " ]\n", "\n", " try:\n", " logger.info(\"Starting near-lossless 10-bit video creation...\")\n", " process = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n", " \n", " encoding_speed = None\n", " \n", " for line in process.stderr:\n", " print(line, end='') # Print FFmpeg output in real-time\n", " \n", " speed_match = re.search(r'speed=\\s*([\\d.]+)x', line)\n", " if speed_match:\n", " encoding_speed = float(speed_match.group(1))\n", " \n", " process.wait()\n", " \n", " if encoding_speed:\n", " logger.info(f\"Encoding speed: {encoding_speed:.2f}x\")\n", " \n", " if process.returncode == 0:\n", " logger.info(f\"Video created successfully: {output_file}\")\n", " \n", " probe_command = ['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_name,width,height,duration,bit_rate,profile', '-of', 'default=noprint_wrappers=1', output_file]\n", " probe_result = subprocess.run(probe_command, capture_output=True, text=True)\n", " logger.info(f\"Video properties:\\n{probe_result.stdout}\")\n", " \n", " duration_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', output_file]\n", " duration_result = subprocess.run(duration_command, capture_output=True, text=True)\n", " actual_duration = float(duration_result.stdout.strip())\n", " logger.info(f\"Actual video duration: {actual_duration:.2f} seconds\")\n", " if abs(actual_duration - expected_duration) > 1:\n", " logger.warning(f\"Video duration mismatch. Expected: {expected_duration:.2f}, Actual: {actual_duration:.2f}\")\n", " else:\n", " logger.info(\"Video duration check passed.\")\n", " else:\n", " logger.error(f\"Error during video creation. FFmpeg returned code {process.returncode}\")\n", "\n", " except subprocess.CalledProcessError as e:\n", " logger.error(f\"Error during video creation: {e}\")\n", " logger.error(f\"FFmpeg error output:\\n{e.stderr}\")\n", "\n", "if __name__ == \"__main__\":\n", " input_folder = 'train'\n", " output_file = 'near_lossless_output.mp4'\n", " fps = 30\n", " frames_per_image = 3\n", " crf = 18 # Very low CRF for near-lossless quality (0 is lossless, but often overkill)\n", "\n", " create_near_lossless_h265_video(input_folder, output_file, fps, frames_per_image, crf)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Transfer File" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import subprocess\n", "import logging\n", "from glob import glob\n", "import re\n", "\n", "# Configure logging\n", "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n", "logger = logging.getLogger(__name__)\n", "\n", "def create_high_quality_video(input_folder, output_file, fps=60, frames_per_image=3, codec='ffv1'):\n", " if not os.path.exists(input_folder):\n", " logger.error(f\"Input folder '{input_folder}' does not exist.\")\n", " return\n", "\n", " png_files = sorted(glob(os.path.join(input_folder, '*.png')))\n", " if not png_files:\n", " logger.error(f\"No PNG files found in {input_folder}\")\n", " return\n", "\n", " num_images = len(png_files)\n", " logger.info(f\"Found {num_images} PNG files.\")\n", "\n", " # Calculate expected duration\n", " expected_duration = (num_images * frames_per_image) / fps\n", " logger.info(f\"Expected duration: {expected_duration:.2f} seconds\")\n", "\n", " # Base FFmpeg command\n", " ffmpeg_command = [\n", " 'ffmpeg',\n", " '-framerate', f'{1/(frames_per_image/fps)}', # Input framerate\n", " '-i', os.path.join(input_folder, '%*.png'), # Input pattern for all PNG files\n", " '-fps_mode', 'vfr',\n", " ]\n", "\n", " # Codec-specific settings\n", " if codec == 'ffv1':\n", " output_file = output_file.rsplit('.', 1)[0] + '.mkv' # FFV1 is typically used with MKV container\n", " ffmpeg_command.extend([\n", " '-c:v', 'ffv1',\n", " '-level', '3',\n", " '-coder', '1',\n", " '-context', '1',\n", " '-g', '1',\n", " '-slices', '24',\n", " '-slicecrc', '1'\n", " ])\n", " logger.info(\"Using FFV1 codec (lossless)\")\n", " elif codec == 'prores':\n", " output_file = output_file.rsplit('.', 1)[0] + '.mov' # ProRes is typically used with MOV container\n", " ffmpeg_command.extend([\n", " '-c:v', 'prores_ks',\n", " '-profile:v', '4444', # Highest quality ProRes\n", " '-qscale:v', '5' # Lower values mean higher quality, 5 is very high quality\n", " ])\n", " logger.info(\"Using ProRes codec (near-lossless)\")\n", " else:\n", " logger.error(f\"Unsupported codec: {codec}\")\n", " return\n", "\n", " ffmpeg_command.extend(['-y', output_file])\n", "\n", " try:\n", " logger.info(f\"Starting high-quality video creation with {codec} codec...\")\n", " process = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n", " \n", " encoding_speed = None\n", " \n", " for line in process.stderr:\n", " print(line, end='') # Print FFmpeg output in real-time\n", " \n", " speed_match = re.search(r'speed=\\s*([\\d.]+)x', line)\n", " if speed_match:\n", " encoding_speed = float(speed_match.group(1))\n", " \n", " process.wait()\n", " \n", " if encoding_speed:\n", " logger.info(f\"Encoding speed: {encoding_speed:.4f}x\")\n", " \n", " if process.returncode == 0:\n", " logger.info(f\"Video created successfully: {output_file}\")\n", " \n", " probe_command = ['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_name,width,height,duration,bit_rate', '-of', 'default=noprint_wrappers=1', output_file]\n", " probe_result = subprocess.run(probe_command, capture_output=True, text=True)\n", " logger.info(f\"Video properties:\\n{probe_result.stdout}\")\n", " \n", " duration_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', output_file]\n", " duration_result = subprocess.run(duration_command, capture_output=True, text=True)\n", " actual_duration = float(duration_result.stdout.strip())\n", " logger.info(f\"Actual video duration: {actual_duration:.2f} seconds\")\n", " if abs(actual_duration - expected_duration) > 1:\n", " logger.warning(f\"Video duration mismatch. Expected: {expected_duration:.2f}, Actual: {actual_duration:.2f}\")\n", " else:\n", " logger.info(\"Video duration check passed.\")\n", " else:\n", " logger.error(f\"Error during video creation. FFmpeg returned code {process.returncode}\")\n", "\n", " except subprocess.CalledProcessError as e:\n", " logger.error(f\"Error during video creation: {e}\")\n", " logger.error(f\"FFmpeg error output:\\n{e.stderr}\")\n", "\n", "if __name__ == \"__main__\":\n", " input_folder = 'train'\n", " output_file = 'high_quality_output.mp4'\n", " fps = 60\n", " frames_per_image = 3\n", " codec = 'prores' # Options: 'ffv1' (lossless) or 'prores' (near-lossless)\n", "\n", " create_high_quality_video(input_folder, output_file, fps, frames_per_image, codec)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.14" } }, "nbformat": 4, "nbformat_minor": 2 }