Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

VideoEd.py 8.9 KB

You have to be logged in to leave a comment. Sign In
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
  1. import subprocess
  2. import numpy as np
  3. import ffmpeg
  4. from pathlib import Path
  5. from core import pathex
  6. from core.interact import interact as io
  7. def extract_video(input_file, output_dir, output_ext=None, fps=None):
  8. input_file_path = Path(input_file)
  9. output_path = Path(output_dir)
  10. if not output_path.exists():
  11. output_path.mkdir(exist_ok=True)
  12. if input_file_path.suffix == '.*':
  13. input_file_path = pathex.get_first_file_by_stem (input_file_path.parent, input_file_path.stem)
  14. else:
  15. if not input_file_path.exists():
  16. input_file_path = None
  17. if input_file_path is None:
  18. io.log_err("input_file not found.")
  19. return
  20. if fps is None:
  21. fps = io.input_int ("Enter FPS", 0, help_message="How many frames of every second of the video will be extracted. 0 - full fps")
  22. if output_ext is None:
  23. output_ext = io.input_str ("Output image format", "png", ["png","jpg"], help_message="png is lossless, but extraction is x10 slower for HDD, requires x10 more disk space than jpg.")
  24. for filename in pathex.get_image_paths (output_path, ['.'+output_ext]):
  25. Path(filename).unlink()
  26. job = ffmpeg.input(str(input_file_path))
  27. kwargs = {'pix_fmt': 'rgb24'}
  28. if fps != 0:
  29. kwargs.update ({'r':str(fps)})
  30. if output_ext == 'jpg':
  31. kwargs.update ({'q:v':'2'}) #highest quality for jpg
  32. job = job.output( str (output_path / ('%5d.'+output_ext)), **kwargs )
  33. try:
  34. job = job.run()
  35. except:
  36. io.log_err ("ffmpeg fail, job commandline:" + str(job.compile()) )
  37. def cut_video ( input_file, from_time=None, to_time=None, audio_track_id=None, bitrate=None):
  38. input_file_path = Path(input_file)
  39. if input_file_path is None:
  40. io.log_err("input_file not found.")
  41. return
  42. output_file_path = input_file_path.parent / (input_file_path.stem + "_cut" + input_file_path.suffix)
  43. if from_time is None:
  44. from_time = io.input_str ("From time", "00:00:00.000")
  45. if to_time is None:
  46. to_time = io.input_str ("To time", "00:00:00.000")
  47. if audio_track_id is None:
  48. audio_track_id = io.input_int ("Specify audio track id.", 0)
  49. if bitrate is None:
  50. bitrate = max (1, io.input_int ("Bitrate of output file in MB/s", 25) )
  51. kwargs = {"c:v": "libx264",
  52. "b:v": "%dM" %(bitrate),
  53. "pix_fmt": "yuv420p",
  54. }
  55. job = ffmpeg.input(str(input_file_path), ss=from_time, to=to_time)
  56. job_v = job['v:0']
  57. job_a = job['a:' + str(audio_track_id) + '?' ]
  58. job = ffmpeg.output(job_v, job_a, str(output_file_path), **kwargs).overwrite_output()
  59. try:
  60. job = job.run()
  61. except:
  62. io.log_err ("ffmpeg fail, job commandline:" + str(job.compile()) )
  63. def denoise_image_sequence( input_dir, ext=None, factor=None ):
  64. input_path = Path(input_dir)
  65. if not input_path.exists():
  66. io.log_err("input_dir not found.")
  67. return
  68. image_paths = [ Path(filepath) for filepath in pathex.get_image_paths(input_path) ]
  69. # Check extension of all images
  70. image_paths_suffix = None
  71. for filepath in image_paths:
  72. if image_paths_suffix is None:
  73. image_paths_suffix = filepath.suffix
  74. else:
  75. if filepath.suffix != image_paths_suffix:
  76. io.log_err(f"All images in {input_path.name} should be with the same extension.")
  77. return
  78. if factor is None:
  79. factor = np.clip ( io.input_int ("Denoise factor?", 7, add_info="1-20"), 1, 20 )
  80. # Rename to temporary filenames
  81. for i,filepath in io.progress_bar_generator( enumerate(image_paths), "Renaming", leave=False):
  82. src = filepath
  83. dst = filepath.parent / ( f'{i+1:06}_{filepath.name}' )
  84. try:
  85. src.rename (dst)
  86. except:
  87. io.log_error ('fail to rename %s' % (src.name) )
  88. return
  89. # Rename to sequental filenames
  90. for i,filepath in io.progress_bar_generator( enumerate(image_paths), "Renaming", leave=False):
  91. src = filepath.parent / ( f'{i+1:06}_{filepath.name}' )
  92. dst = filepath.parent / ( f'{i+1:06}{filepath.suffix}' )
  93. try:
  94. src.rename (dst)
  95. except:
  96. io.log_error ('fail to rename %s' % (src.name) )
  97. return
  98. # Process image sequence in ffmpeg
  99. kwargs = {}
  100. if image_paths_suffix == '.jpg':
  101. kwargs.update ({'q:v':'2'})
  102. job = ( ffmpeg
  103. .input(str ( input_path / ('%6d'+image_paths_suffix) ) )
  104. .filter("hqdn3d", factor, factor, 5,5)
  105. .output(str ( input_path / ('%6d'+image_paths_suffix) ), **kwargs )
  106. )
  107. try:
  108. job = job.run()
  109. except:
  110. io.log_err ("ffmpeg fail, job commandline:" + str(job.compile()) )
  111. # Rename to temporary filenames
  112. for i,filepath in io.progress_bar_generator( enumerate(image_paths), "Renaming", leave=False):
  113. src = filepath.parent / ( f'{i+1:06}{filepath.suffix}' )
  114. dst = filepath.parent / ( f'{i+1:06}_{filepath.name}' )
  115. try:
  116. src.rename (dst)
  117. except:
  118. io.log_error ('fail to rename %s' % (src.name) )
  119. return
  120. # Rename to initial filenames
  121. for i,filepath in io.progress_bar_generator( enumerate(image_paths), "Renaming", leave=False):
  122. src = filepath.parent / ( f'{i+1:06}_{filepath.name}' )
  123. dst = filepath
  124. try:
  125. src.rename (dst)
  126. except:
  127. io.log_error ('fail to rename %s' % (src.name) )
  128. return
  129. def video_from_sequence( input_dir, output_file, reference_file=None, ext=None, fps=None, bitrate=None, include_audio=False, lossless=None ):
  130. input_path = Path(input_dir)
  131. output_file_path = Path(output_file)
  132. reference_file_path = Path(reference_file) if reference_file is not None else None
  133. if not input_path.exists():
  134. io.log_err("input_dir not found.")
  135. return
  136. if not output_file_path.parent.exists():
  137. output_file_path.parent.mkdir(parents=True, exist_ok=True)
  138. return
  139. out_ext = output_file_path.suffix
  140. if ext is None:
  141. ext = io.input_str ("Input image format (extension)", "png")
  142. if lossless is None:
  143. lossless = io.input_bool ("Use lossless codec", False)
  144. video_id = None
  145. audio_id = None
  146. ref_in_a = None
  147. if reference_file_path is not None:
  148. if reference_file_path.suffix == '.*':
  149. reference_file_path = pathex.get_first_file_by_stem (reference_file_path.parent, reference_file_path.stem)
  150. else:
  151. if not reference_file_path.exists():
  152. reference_file_path = None
  153. if reference_file_path is None:
  154. io.log_err("reference_file not found.")
  155. return
  156. #probing reference file
  157. probe = ffmpeg.probe (str(reference_file_path))
  158. #getting first video and audio streams id with fps
  159. for stream in probe['streams']:
  160. if video_id is None and stream['codec_type'] == 'video':
  161. video_id = stream['index']
  162. fps = stream['r_frame_rate']
  163. if audio_id is None and stream['codec_type'] == 'audio':
  164. audio_id = stream['index']
  165. if audio_id is not None:
  166. #has audio track
  167. ref_in_a = ffmpeg.input (str(reference_file_path))[str(audio_id)]
  168. if fps is None:
  169. #if fps not specified and not overwritten by reference-file
  170. fps = max (1, io.input_int ("Enter FPS", 25) )
  171. if not lossless and bitrate is None:
  172. bitrate = max (1, io.input_int ("Bitrate of output file in MB/s", 16) )
  173. input_image_paths = pathex.get_image_paths(input_path)
  174. i_in = ffmpeg.input('pipe:', format='image2pipe', r=fps)
  175. output_args = [i_in]
  176. if include_audio and ref_in_a is not None:
  177. output_args += [ref_in_a]
  178. output_args += [str (output_file_path)]
  179. output_kwargs = {}
  180. if lossless:
  181. output_kwargs.update ({"c:v": "libx264",
  182. "crf": "0",
  183. "pix_fmt": "yuv420p",
  184. })
  185. else:
  186. output_kwargs.update ({"c:v": "libx264",
  187. "b:v": "%dM" %(bitrate),
  188. "pix_fmt": "yuv420p",
  189. })
  190. if include_audio and ref_in_a is not None:
  191. output_kwargs.update ({"c:a": "aac",
  192. "b:a": "192k",
  193. "ar" : "48000",
  194. "strict": "experimental"
  195. })
  196. job = ( ffmpeg.output(*output_args, **output_kwargs).overwrite_output() )
  197. try:
  198. job_run = job.run_async(pipe_stdin=True)
  199. for image_path in input_image_paths:
  200. with open (image_path, "rb") as f:
  201. image_bytes = f.read()
  202. job_run.stdin.write (image_bytes)
  203. job_run.stdin.close()
  204. job_run.wait()
  205. except:
  206. io.log_err ("ffmpeg fail, job commandline:" + str(job.compile()) )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...