Datasets:
File size: 11,676 Bytes
2acbc78 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Create Video!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pip install 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', 'proxy', # Use ProRes 422 Proxy profile\n",
" '-qscale:v', '11' # Adjust quality scale; higher values mean lower quality. 11 is typical for proxy quality.\n",
"])\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
}
|