Jordan Legg commited on
Commit
5c012db
·
1 Parent(s): 5784d85

first prod level script

Browse files
Files changed (1) hide show
  1. create-video.ipynb +106 -94
create-video.ipynb CHANGED
@@ -9,29 +9,9 @@
9
  },
10
  {
11
  "cell_type": "code",
12
- "execution_count": 2,
13
  "metadata": {},
14
- "outputs": [
15
- {
16
- "name": "stdout",
17
- "output_type": "stream",
18
- "text": [
19
- "Collecting opencv-python\n",
20
- " Downloading opencv_python-4.10.0.84-cp37-abi3-macosx_12_0_x86_64.whl (56.5 MB)\n",
21
- "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m56.5/56.5 MB\u001b[0m \u001b[31m24.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
22
- "\u001b[?25hCollecting opencv-python-headless\n",
23
- " Downloading opencv_python_headless-4.10.0.84-cp37-abi3-macosx_12_0_x86_64.whl (56.5 MB)\n",
24
- "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m56.5/56.5 MB\u001b[0m \u001b[31m27.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
25
- "\u001b[?25hRequirement already satisfied: numpy>=1.17.0 in /Users/jordanlegg/.pyenv/versions/3.10.14/lib/python3.10/site-packages (from opencv-python) (1.26.4)\n",
26
- "Installing collected packages: opencv-python-headless, opencv-python\n",
27
- "Successfully installed opencv-python-4.10.0.84 opencv-python-headless-4.10.0.84\n",
28
- "\n",
29
- "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.2\u001b[0m\n",
30
- "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
31
- "Note: you may need to restart the kernel to use updated packages.\n"
32
- ]
33
- }
34
- ],
35
  "source": [
36
  "pip install opencv-python opencv-python-headless # If you do not need GUI features\n"
37
  ]
@@ -45,98 +25,130 @@
45
  },
46
  {
47
  "cell_type": "code",
48
- "execution_count": 7,
49
  "metadata": {},
50
  "outputs": [
51
  {
52
  "name": "stderr",
53
  "output_type": "stream",
54
  "text": [
55
- "2024-08-05 18:00:36,460 - INFO - Fetching images from folder...\n",
56
- "2024-08-05 18:00:56,576 - INFO - Creating video from images...\n",
57
- "python(92560) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
58
- "python(92561) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
59
- "python(92562) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
60
- "python(92563) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
61
- "python(92564) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
62
- "python(92565) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
63
- "python(92566) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
64
- "python(92567) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
65
- "python(92568) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
66
- "python(92569) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
67
- "python(92570) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
68
- "python(92571) MallocStackLogging: can't turn off malloc stack logging because it was not enabled.\n",
69
- "2024-08-05 18:01:38,285 - INFO - Video saved as demo.mp4\n"
70
  ]
71
  }
72
  ],
73
  "source": [
74
- "import cv2\n",
75
  "import os\n",
 
76
  "import logging\n",
77
- "import multiprocessing\n",
78
- "from concurrent.futures import ProcessPoolExecutor\n",
79
- "from video_helpers import write_frames # Import the helper function\n",
80
  "\n",
81
  "# Configure logging\n",
82
  "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n",
 
83
  "\n",
84
- "def get_images_from_folder(folder):\n",
85
- " images = []\n",
86
- " for filename in sorted(os.listdir(folder)):\n",
87
- " if filename.endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff')):\n",
88
- " img = cv2.imread(os.path.join(folder, filename))\n",
89
- " if img is not None:\n",
90
- " images.append(img)\n",
91
- " return images\n",
92
- "\n",
93
- "def create_video_from_images(images, output_file, fps, frames_per_image):\n",
94
- " if not images:\n",
95
- " logging.error(\"No images found in the folder.\")\n",
96
  " return\n",
97
  "\n",
98
- " height, width, layers = images[0].shape\n",
99
- " size = (width, height)\n",
100
- " \n",
101
- " # Temporary video file list\n",
102
- " temp_files = []\n",
103
- "\n",
104
- " # Using a process pool to parallelize writing frames\n",
105
- " with ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) as executor:\n",
106
- " for i, image in enumerate(images):\n",
107
- " temp_file = f'temp_{i}.mp4'\n",
108
- " temp_files.append(temp_file)\n",
109
- " executor.submit(write_frames, image, temp_file, fps, frames_per_image, size)\n",
110
- " \n",
111
- " # Combine all temporary files into one\n",
112
- " out = cv2.VideoWriter(output_file, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  " \n",
114
- " for temp_file in temp_files:\n",
115
- " cap = cv2.VideoCapture(temp_file)\n",
116
- " while cap.isOpened():\n",
117
- " ret, frame = cap.read()\n",
118
- " if not ret:\n",
119
- " break\n",
120
- " out.write(frame)\n",
121
- " cap.release()\n",
122
- " os.remove(temp_file)\n",
123
  " \n",
124
- " out.release()\n",
125
- " logging.info(f\"Video saved as {output_file}\")\n",
126
- "\n",
127
- "# Parameters\n",
128
- "folder = 'train' # Folder containing the images\n",
129
- "output_file = 'demo.mp4' # Output video file\n",
130
- "fps = 60 # Frames per second\n",
131
- "frames_per_image = 3 # Each image will be displayed for 3 frames\n",
132
- "\n",
133
- "# Get images from the folder\n",
134
- "logging.info('Fetching images from folder...')\n",
135
- "images = get_images_from_folder(folder)\n",
136
- "\n",
137
- "# Create video from images\n",
138
- "logging.info('Creating video from images...')\n",
139
- "create_video_from_images(images, output_file, fps, frames_per_image)\n",
 
140
  "\n",
141
  "\n"
142
  ]
 
9
  },
10
  {
11
  "cell_type": "code",
12
+ "execution_count": null,
13
  "metadata": {},
14
+ "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  "source": [
16
  "pip install opencv-python opencv-python-headless # If you do not need GUI features\n"
17
  ]
 
25
  },
26
  {
27
  "cell_type": "code",
28
+ "execution_count": 1,
29
  "metadata": {},
30
  "outputs": [
31
  {
32
  "name": "stderr",
33
  "output_type": "stream",
34
  "text": [
35
+ "2024-08-05 19:36:09,033 - INFO - Found 911 PNG files.\n",
36
+ "2024-08-05 19:36:09,035 - INFO - Starting video creation...\n",
37
+ "2024-08-05 19:36:24,399 - INFO - FFmpeg output:\n",
38
+ "\n",
39
+ "2024-08-05 19:36:24,400 - INFO - Video created successfully: output_production.mp4\n",
40
+ "2024-08-05 19:36:24,483 - INFO - Video properties:\n",
41
+ "codec_name=hevc\n",
42
+ "width=1024\n",
43
+ "height=1024\n",
44
+ "duration=0.160000\n",
45
+ "\n",
46
+ "2024-08-05 19:36:25,344 - INFO - Video playback check passed.\n"
 
 
 
47
  ]
48
  }
49
  ],
50
  "source": [
 
51
  "import os\n",
52
+ "import subprocess\n",
53
  "import logging\n",
54
+ "from glob import glob\n",
 
 
55
  "\n",
56
  "# Configure logging\n",
57
  "logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n",
58
+ "logger = logging.getLogger(__name__)\n",
59
  "\n",
60
+ "def create_h265_video(input_folder, output_file, fps=30, frames_per_image=3):\n",
61
+ " if not os.path.exists(input_folder):\n",
62
+ " logger.error(f\"Input folder '{input_folder}' does not exist.\")\n",
 
 
 
 
 
 
 
 
 
63
  " return\n",
64
  "\n",
65
+ " png_files = sorted(glob(os.path.join(input_folder, '*.png')))\n",
66
+ " if not png_files:\n",
67
+ " logger.error(f\"No PNG files found in {input_folder}\")\n",
68
+ " return\n",
69
+ "\n",
70
+ " num_images = len(png_files)\n",
71
+ " logger.info(f\"Found {num_images} PNG files.\")\n",
72
+ "\n",
73
+ " # Calculate expected duration\n",
74
+ " expected_duration = (num_images * frames_per_image) / fps\n",
75
+ " logger.info(f\"Expected duration: {expected_duration:.2f} seconds\")\n",
76
+ "\n",
77
+ " # Create a temporary file list\n",
78
+ " with open('temp_file_list.txt', 'w') as f:\n",
79
+ " for file in png_files:\n",
80
+ " f.write(f\"file '{file}'\\n\")\n",
81
+ " f.write(f\"duration {frames_per_image/fps:.6f}\\n\")\n",
82
+ "\n",
83
+ " # FFmpeg command to create video\n",
84
+ " ffmpeg_command = [\n",
85
+ " 'ffmpeg',\n",
86
+ " '-f', 'concat',\n",
87
+ " '-safe', '0',\n",
88
+ " '-i', 'temp_file_list.txt',\n",
89
+ " '-vsync', 'vfr',\n",
90
+ " '-pix_fmt', 'yuv420p', # Ensure compatible color space\n",
91
+ " '-color_range', '1', # Ensure full color range\n",
92
+ " '-color_primaries', '1',\n",
93
+ " '-color_trc', '1',\n",
94
+ " '-colorspace', '1',\n",
95
+ " '-c:v', 'libx265',\n",
96
+ " '-crf', '23',\n",
97
+ " '-preset', 'medium',\n",
98
+ " '-tag:v', 'hvc1',\n",
99
+ " '-y',\n",
100
+ " output_file\n",
101
+ " ]\n",
102
+ "\n",
103
+ " try:\n",
104
+ " logger.info(\"Starting video creation...\")\n",
105
+ " result = subprocess.run(ffmpeg_command, check=True, capture_output=True, text=True)\n",
106
+ " logger.info(f\"FFmpeg output:\\n{result.stdout}\")\n",
107
+ " \n",
108
+ " if os.path.exists(output_file):\n",
109
+ " logger.info(f\"Video created successfully: {output_file}\")\n",
110
+ " \n",
111
+ " # Verify the output\n",
112
+ " probe_command = ['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_name,width,height,duration', '-of', 'default=noprint_wrappers=1', output_file]\n",
113
+ " probe_result = subprocess.run(probe_command, capture_output=True, text=True)\n",
114
+ " logger.info(f\"Video properties:\\n{probe_result.stdout}\")\n",
115
+ " \n",
116
+ " # Check if the video is playable and has correct duration\n",
117
+ " play_check_command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', output_file]\n",
118
+ " try:\n",
119
+ " duration_result = subprocess.run(play_check_command, check=True, capture_output=True, text=True)\n",
120
+ " actual_duration = float(duration_result.stdout.strip())\n",
121
+ " logger.info(f\"Actual video duration: {actual_duration:.2f} seconds\")\n",
122
+ " if abs(actual_duration - expected_duration) > 1: # Allow 1 second tolerance\n",
123
+ " logger.warning(f\"Video duration mismatch. Expected: {expected_duration:.2f}, Actual: {actual_duration:.2f}\")\n",
124
+ " else:\n",
125
+ " logger.info(\"Video duration check passed.\")\n",
126
+ " except subprocess.CalledProcessError:\n",
127
+ " logger.error(\"Video duration check failed.\")\n",
128
+ " else:\n",
129
+ " logger.error(f\"Output file was not created: {output_file}\")\n",
130
  " \n",
131
+ " except subprocess.CalledProcessError as e:\n",
132
+ " logger.error(f\"Error during video creation: {e}\")\n",
133
+ " logger.error(f\"FFmpeg error output:\\n{e.stderr}\")\n",
 
 
 
 
 
 
134
  " \n",
135
+ " finally:\n",
136
+ " # Clean up\n",
137
+ " if os.path.exists('temp_file_list.txt'):\n",
138
+ " os.remove('temp_file_list.txt')\n",
139
+ "\n",
140
+ "if __name__ == \"__main__\":\n",
141
+ " input_folder = 'train'\n",
142
+ " output_file = 'output_production.mp4'\n",
143
+ " fps = 30\n",
144
+ " frames_per_image = 3\n",
145
+ "\n",
146
+ " create_h265_video(input_folder, output_file, fps, frames_per_image)\n",
147
+ "\n",
148
+ "\n",
149
+ "\n",
150
+ "\n",
151
+ "\n",
152
  "\n",
153
  "\n"
154
  ]