nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/cuts.py
FramesMatches.filter
(self, condition)
return FramesMatches(filter(condition, self))
Return a FramesMatches object obtained by filtering out the FramesMatch which do not satistify a condition. Parameters ---------- condition : func Function which takes a FrameMatch object as parameter and returns a bool. Examples -------- >>> # Only keep the matches corresponding to (> 1 second) sequences. >>> new_matches = matches.filter( lambda match: match.time_span > 1)
Return a FramesMatches object obtained by filtering out the FramesMatch which do not satistify a condition.
144
160
def filter(self, condition): """Return a FramesMatches object obtained by filtering out the FramesMatch which do not satistify a condition. Parameters ---------- condition : func Function which takes a FrameMatch object as parameter and returns a bool. Examples -------- >>> # Only keep the matches corresponding to (> 1 second) sequences. >>> new_matches = matches.filter( lambda match: match.time_span > 1) """ return FramesMatches(filter(condition, self))
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/cuts.py#L144-L160
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
98.290598
17
1
100
14
def filter(self, condition): return FramesMatches(filter(condition, self))
28,467
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/cuts.py
FramesMatches.save
(self, filename)
Save a FramesMatches object to a file. Parameters ---------- filename : str Path to the file in which will be dumped the FramesMatches object data.
Save a FramesMatches object to a file.
162
176
def save(self, filename): """Save a FramesMatches object to a file. Parameters ---------- filename : str Path to the file in which will be dumped the FramesMatches object data. """ np.savetxt( filename, np.array([np.array(list(e)) for e in self]), fmt="%.03f", delimiter="\t", )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/cuts.py#L162-L176
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
98.290598
15
2
100
7
def save(self, filename): np.savetxt( filename, np.array([np.array(list(e)) for e in self]), fmt="%.03f", delimiter="\t", )
28,468
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/cuts.py
FramesMatches.load
(filename)
return FramesMatches(mfs)
Load a FramesMatches object from a file. Parameters ---------- filename : str Path to the file to use loading a FramesMatches object. Examples -------- >>> matching_frames = FramesMatches.load("somefile")
Load a FramesMatches object from a file.
179
194
def load(filename): """Load a FramesMatches object from a file. Parameters ---------- filename : str Path to the file to use loading a FramesMatches object. Examples -------- >>> matching_frames = FramesMatches.load("somefile") """ arr = np.loadtxt(filename) mfs = [FramesMatch(*e) for e in arr] return FramesMatches(mfs)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/cuts.py#L179-L194
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
98.290598
16
2
100
11
def load(filename): arr = np.loadtxt(filename) mfs = [FramesMatch(*e) for e in arr] return FramesMatches(mfs)
28,469
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/cuts.py
FramesMatches.from_clip
(clip, distance_threshold, max_duration, fps=None, logger="bar")
return FramesMatches([FramesMatch(*e) for e in matching_frames])
Finds all the frames that look alike in a clip, for instance to make a looping GIF. Parameters ---------- clip : moviepy.video.VideoClip.VideoClip A MoviePy video clip. distance_threshold : float Distance above which a match is rejected. max_duration : float Maximal duration (in seconds) between two matching frames. fps : int, optional Frames per second (default will be ``clip.fps``). logger : str, optional Either ``"bar"`` for progress bar or ``None`` or any Proglog logger. Returns ------- FramesMatches All pairs of frames with ``end_time - start_time < max_duration`` and whose distance is under ``distance_threshold``. Examples -------- We find all matching frames in a given video and turn the best match with a duration of 1.5 seconds or more into a GIF: >>> from moviepy import VideoFileClip >>> from moviepy.video.tools.cuts import FramesMatches >>> >>> clip = VideoFileClip("foo.mp4").resize(width=200) >>> matches = FramesMatches.from_clip( ... clip, distance_threshold=10, max_duration=3, # will take time ... ) >>> best = matches.filter(lambda m: m.time_span > 1.5).best() >>> clip.subclip(best.start_time, best.end_time).write_gif("foo.gif")
Finds all the frames that look alike in a clip, for instance to make a looping GIF.
197
308
def from_clip(clip, distance_threshold, max_duration, fps=None, logger="bar"): """Finds all the frames that look alike in a clip, for instance to make a looping GIF. Parameters ---------- clip : moviepy.video.VideoClip.VideoClip A MoviePy video clip. distance_threshold : float Distance above which a match is rejected. max_duration : float Maximal duration (in seconds) between two matching frames. fps : int, optional Frames per second (default will be ``clip.fps``). logger : str, optional Either ``"bar"`` for progress bar or ``None`` or any Proglog logger. Returns ------- FramesMatches All pairs of frames with ``end_time - start_time < max_duration`` and whose distance is under ``distance_threshold``. Examples -------- We find all matching frames in a given video and turn the best match with a duration of 1.5 seconds or more into a GIF: >>> from moviepy import VideoFileClip >>> from moviepy.video.tools.cuts import FramesMatches >>> >>> clip = VideoFileClip("foo.mp4").resize(width=200) >>> matches = FramesMatches.from_clip( ... clip, distance_threshold=10, max_duration=3, # will take time ... ) >>> best = matches.filter(lambda m: m.time_span > 1.5).best() >>> clip.subclip(best.start_time, best.end_time).write_gif("foo.gif") """ N_pixels = clip.w * clip.h * 3 def dot_product(F1, F2): return (F1 * F2).sum() / N_pixels frame_dict = {} # will store the frames and their mutual distances def distance(t1, t2): uv = dot_product(frame_dict[t1]["frame"], frame_dict[t2]["frame"]) u, v = frame_dict[t1]["|F|sq"], frame_dict[t2]["|F|sq"] return np.sqrt(u + v - 2 * uv) matching_frames = [] # the final result. for (t, frame) in clip.iter_frames(with_times=True, logger=logger): flat_frame = 1.0 * frame.flatten() F_norm_sq = dot_product(flat_frame, flat_frame) F_norm = np.sqrt(F_norm_sq) for t2 in list(frame_dict.keys()): # forget old frames, add 't' to the others frames # check for early rejections based on differing norms if (t - t2) > max_duration: frame_dict.pop(t2) else: frame_dict[t2][t] = { "min": abs(frame_dict[t2]["|F|"] - F_norm), "max": frame_dict[t2]["|F|"] + F_norm, } frame_dict[t2][t]["rejected"] = ( frame_dict[t2][t]["min"] > distance_threshold ) t_F = sorted(frame_dict.keys()) frame_dict[t] = {"frame": flat_frame, "|F|sq": F_norm_sq, "|F|": F_norm} for i, t2 in enumerate(t_F): # Compare F(t) to all the previous frames if frame_dict[t2][t]["rejected"]: continue dist = distance(t, t2) frame_dict[t2][t]["min"] = frame_dict[t2][t]["max"] = dist frame_dict[t2][t]["rejected"] = dist >= distance_threshold for t3 in t_F[i + 1 :]: # For all the next times t3, use d(F(t), F(end_time)) to # update the bounds on d(F(t), F(t3)). See if you can # conclude on whether F(t) and F(t3) match. t3t, t2t3 = frame_dict[t3][t], frame_dict[t2][t3] t3t["max"] = min(t3t["max"], dist + t2t3["max"]) t3t["min"] = max(t3t["min"], dist - t2t3["max"], t2t3["min"] - dist) if t3t["min"] > distance_threshold: t3t["rejected"] = True # Store all the good matches (end_time,t) matching_frames += [ (t1, t, frame_dict[t1][t]["min"], frame_dict[t1][t]["max"]) for t1 in frame_dict if (t1 != t) and not frame_dict[t1][t]["rejected"] ] return FramesMatches([FramesMatch(*e) for e in matching_frames])
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/cuts.py#L197-L308
46
[ 0, 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 ]
100
[]
0
true
98.290598
112
13
100
43
def from_clip(clip, distance_threshold, max_duration, fps=None, logger="bar"): N_pixels = clip.w * clip.h * 3 def dot_product(F1, F2): return (F1 * F2).sum() / N_pixels frame_dict = {} # will store the frames and their mutual distances def distance(t1, t2): uv = dot_product(frame_dict[t1]["frame"], frame_dict[t2]["frame"]) u, v = frame_dict[t1]["|F|sq"], frame_dict[t2]["|F|sq"] return np.sqrt(u + v - 2 * uv) matching_frames = [] # the final result. for (t, frame) in clip.iter_frames(with_times=True, logger=logger): flat_frame = 1.0 * frame.flatten() F_norm_sq = dot_product(flat_frame, flat_frame) F_norm = np.sqrt(F_norm_sq) for t2 in list(frame_dict.keys()): # forget old frames, add 't' to the others frames # check for early rejections based on differing norms if (t - t2) > max_duration: frame_dict.pop(t2) else: frame_dict[t2][t] = { "min": abs(frame_dict[t2]["|F|"] - F_norm), "max": frame_dict[t2]["|F|"] + F_norm, } frame_dict[t2][t]["rejected"] = ( frame_dict[t2][t]["min"] > distance_threshold ) t_F = sorted(frame_dict.keys()) frame_dict[t] = {"frame": flat_frame, "|F|sq": F_norm_sq, "|F|": F_norm} for i, t2 in enumerate(t_F): # Compare F(t) to all the previous frames if frame_dict[t2][t]["rejected"]: continue dist = distance(t, t2) frame_dict[t2][t]["min"] = frame_dict[t2][t]["max"] = dist frame_dict[t2][t]["rejected"] = dist >= distance_threshold for t3 in t_F[i + 1 :]: # For all the next times t3, use d(F(t), F(end_time)) to # update the bounds on d(F(t), F(t3)). See if you can # conclude on whether F(t) and F(t3) match. t3t, t2t3 = frame_dict[t3][t], frame_dict[t2][t3] t3t["max"] = min(t3t["max"], dist + t2t3["max"]) t3t["min"] = max(t3t["min"], dist - t2t3["max"], t2t3["min"] - dist) if t3t["min"] > distance_threshold: t3t["rejected"] = True # Store all the good matches (end_time,t) matching_frames += [ (t1, t, frame_dict[t1][t]["min"], frame_dict[t1][t]["max"]) for t1 in frame_dict if (t1 != t) and not frame_dict[t1][t]["rejected"] ] return FramesMatches([FramesMatch(*e) for e in matching_frames])
28,470
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/cuts.py
FramesMatches.select_scenes
( self, match_threshold, min_time_span, nomatch_threshold=None, time_distance=0 )
return FramesMatches(result)
Select the scenes at which a video clip can be reproduced as the smoothest possible way, mainly oriented for the creation of GIF images. Parameters ---------- match_threshold : float Maximum distance possible between frames. The smaller, the better-looping the GIFs are. min_time_span : float Minimum duration for a scene. Only matches with a duration longer than the value passed to this parameters will be extracted. nomatch_threshold : float, optional Minimum distance possible between frames. If is ``None``, then it is chosen equal to ``match_threshold``. time_distance : float, optional Minimum time offset possible between matches. Returns ------- FramesMatches : New instance of the class with the selected scenes. Examples -------- >>> from pprint import pprint >>> from moviepy.editor import * >>> from moviepy.video.tools.cuts import FramesMatches >>> >>> ch_clip = VideoFileClip("media/chaplin.mp4").subclip(1, 4) >>> clip = concatenate_videoclips([ch_clip.time_mirror(), ch_clip]) >>> >>> result = FramesMatches.from_clip(clip, 10, 3).select_scenes( ... 1, 2, nomatch_threshold=0, ... ) >>> pprint(result) [(1.0000, 4.0000, 0.0000, 0.0000), (1.1600, 3.8400, 0.0000, 0.0000), (1.2800, 3.7200, 0.0000, 0.0000), (1.4000, 3.6000, 0.0000, 0.0000)]
Select the scenes at which a video clip can be reproduced as the smoothest possible way, mainly oriented for the creation of GIF images.
310
408
def select_scenes( self, match_threshold, min_time_span, nomatch_threshold=None, time_distance=0 ): """Select the scenes at which a video clip can be reproduced as the smoothest possible way, mainly oriented for the creation of GIF images. Parameters ---------- match_threshold : float Maximum distance possible between frames. The smaller, the better-looping the GIFs are. min_time_span : float Minimum duration for a scene. Only matches with a duration longer than the value passed to this parameters will be extracted. nomatch_threshold : float, optional Minimum distance possible between frames. If is ``None``, then it is chosen equal to ``match_threshold``. time_distance : float, optional Minimum time offset possible between matches. Returns ------- FramesMatches : New instance of the class with the selected scenes. Examples -------- >>> from pprint import pprint >>> from moviepy.editor import * >>> from moviepy.video.tools.cuts import FramesMatches >>> >>> ch_clip = VideoFileClip("media/chaplin.mp4").subclip(1, 4) >>> clip = concatenate_videoclips([ch_clip.time_mirror(), ch_clip]) >>> >>> result = FramesMatches.from_clip(clip, 10, 3).select_scenes( ... 1, 2, nomatch_threshold=0, ... ) >>> pprint(result) [(1.0000, 4.0000, 0.0000, 0.0000), (1.1600, 3.8400, 0.0000, 0.0000), (1.2800, 3.7200, 0.0000, 0.0000), (1.4000, 3.6000, 0.0000, 0.0000)] """ if nomatch_threshold is None: nomatch_threshold = match_threshold dict_starts = defaultdict(lambda: []) for (start, end, min_distance, max_distance) in self: dict_starts[start].append([end, min_distance, max_distance]) starts_ends = sorted(dict_starts.items(), key=lambda k: k[0]) result = [] min_start = 0 for start, ends_distances in starts_ends: if start < min_start: continue ends = [end for (end, min_distance, max_distance) in ends_distances] great_matches = [ (end, min_distance, max_distance) for (end, min_distance, max_distance) in ends_distances if max_distance < match_threshold ] great_long_matches = [ (end, min_distance, max_distance) for (end, min_distance, max_distance) in great_matches if (end - start) > min_time_span ] if not great_long_matches: continue # No GIF can be made starting at this time poor_matches = { end for (end, min_distance, max_distance) in ends_distances if min_distance > nomatch_threshold } short_matches = {end for end in ends if (end - start) <= 0.6} if not poor_matches.intersection(short_matches): continue end = max(end for (end, min_distance, max_distance) in great_long_matches) end, min_distance, max_distance = next( e for e in great_long_matches if e[0] == end ) result.append(FramesMatch(start, end, min_distance, max_distance)) min_start = start + time_distance return FramesMatches(result)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/cuts.py#L310-L408
46
[ 0, 47, 48, 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 ]
52.525253
[ 49 ]
1.010101
false
98.290598
99
10
98.989899
44
def select_scenes( self, match_threshold, min_time_span, nomatch_threshold=None, time_distance=0 ): if nomatch_threshold is None: nomatch_threshold = match_threshold dict_starts = defaultdict(lambda: []) for (start, end, min_distance, max_distance) in self: dict_starts[start].append([end, min_distance, max_distance]) starts_ends = sorted(dict_starts.items(), key=lambda k: k[0]) result = [] min_start = 0 for start, ends_distances in starts_ends: if start < min_start: continue ends = [end for (end, min_distance, max_distance) in ends_distances] great_matches = [ (end, min_distance, max_distance) for (end, min_distance, max_distance) in ends_distances if max_distance < match_threshold ] great_long_matches = [ (end, min_distance, max_distance) for (end, min_distance, max_distance) in great_matches if (end - start) > min_time_span ] if not great_long_matches: continue # No GIF can be made starting at this time poor_matches = { end for (end, min_distance, max_distance) in ends_distances if min_distance > nomatch_threshold } short_matches = {end for end in ends if (end - start) <= 0.6} if not poor_matches.intersection(short_matches): continue end = max(end for (end, min_distance, max_distance) in great_long_matches) end, min_distance, max_distance = next( e for e in great_long_matches if e[0] == end ) result.append(FramesMatch(start, end, min_distance, max_distance)) min_start = start + time_distance return FramesMatches(result)
28,471
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/cuts.py
FramesMatches.write_gifs
(self, clip, gifs_dir, **kwargs)
Extract the matching frames represented by the instance from a clip and write them as GIFs in a directory, one GIF for each matching frame. Parameters ---------- clip : video.VideoClip.VideoClip A video clip whose frames scenes you want to obtain as GIF images. gif_dir : str Directory in which the GIF images will be written. kwargs Passed as ``clip.write_gif`` optional arguments. Examples -------- >>> import os >>> from pprint import pprint >>> from moviepy.editor import * >>> from moviepy.video.tools.cuts import FramesMatches >>> >>> ch_clip = VideoFileClip("media/chaplin.mp4").subclip(1, 4) >>> clip = concatenate_videoclips([ch_clip.time_mirror(), ch_clip]) >>> >>> result = FramesMatches.from_clip(clip, 10, 3).select_scenes( ... 1, 2, nomatch_threshold=0, ... ) >>> >>> os.mkdir("foo") >>> result.write_gifs(clip, "foo") MoviePy - Building file foo/00000100_00000400.gif with imageio. MoviePy - Building file foo/00000115_00000384.gif with imageio. MoviePy - Building file foo/00000128_00000372.gif with imageio. MoviePy - Building file foo/00000140_00000360.gif with imageio.
Extract the matching frames represented by the instance from a clip and write them as GIFs in a directory, one GIF for each matching frame.
410
450
def write_gifs(self, clip, gifs_dir, **kwargs): """Extract the matching frames represented by the instance from a clip and write them as GIFs in a directory, one GIF for each matching frame. Parameters ---------- clip : video.VideoClip.VideoClip A video clip whose frames scenes you want to obtain as GIF images. gif_dir : str Directory in which the GIF images will be written. kwargs Passed as ``clip.write_gif`` optional arguments. Examples -------- >>> import os >>> from pprint import pprint >>> from moviepy.editor import * >>> from moviepy.video.tools.cuts import FramesMatches >>> >>> ch_clip = VideoFileClip("media/chaplin.mp4").subclip(1, 4) >>> clip = concatenate_videoclips([ch_clip.time_mirror(), ch_clip]) >>> >>> result = FramesMatches.from_clip(clip, 10, 3).select_scenes( ... 1, 2, nomatch_threshold=0, ... ) >>> >>> os.mkdir("foo") >>> result.write_gifs(clip, "foo") MoviePy - Building file foo/00000100_00000400.gif with imageio. MoviePy - Building file foo/00000115_00000384.gif with imageio. MoviePy - Building file foo/00000128_00000372.gif with imageio. MoviePy - Building file foo/00000140_00000360.gif with imageio. """ for (start, end, _, _) in self: name = "%s/%08d_%08d.gif" % (gifs_dir, 100 * start, 100 * end) clip.subclip(start, end).write_gif(name, **kwargs)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/cuts.py#L410-L450
46
[ 0, 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 ]
100
[]
0
true
98.290598
41
2
100
36
def write_gifs(self, clip, gifs_dir, **kwargs): for (start, end, _, _) in self: name = "%s/%08d_%08d.gif" % (gifs_dir, 100 * start, 100 * end) clip.subclip(start, end).write_gif(name, **kwargs)
28,472
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/segmenting.py
find_objects
(clip, size_threshold=500, preview=False)
return letters
Returns a list of ImageClips representing each a separate object on the screen. Parameters ---------- clip : video.VideoClip.ImageClip MoviePy video clip where the objects will be searched. size_threshold : float, optional Minimum size of what is considered an object. All objects found with ``size < size_threshold`` will be considered false positives and will be removed. preview : bool, optional Previews with matplotlib the different objects found in the image before applying the size threshold. Requires matplotlib installed. Examples -------- >>> clip = ImageClip("media/afterimage.png") >>> objects = find_objects(clip) >>> >>> print(len(objects)) >>> print([obj_.screenpos for obj_ in objects])
Returns a list of ImageClips representing each a separate object on the screen.
9
81
def find_objects(clip, size_threshold=500, preview=False): """Returns a list of ImageClips representing each a separate object on the screen. Parameters ---------- clip : video.VideoClip.ImageClip MoviePy video clip where the objects will be searched. size_threshold : float, optional Minimum size of what is considered an object. All objects found with ``size < size_threshold`` will be considered false positives and will be removed. preview : bool, optional Previews with matplotlib the different objects found in the image before applying the size threshold. Requires matplotlib installed. Examples -------- >>> clip = ImageClip("media/afterimage.png") >>> objects = find_objects(clip) >>> >>> print(len(objects)) >>> print([obj_.screenpos for obj_ in objects]) """ image = clip.get_frame(0) if not clip.mask: # pragma: no cover clip = clip.add_mask() mask = clip.mask.get_frame(0) labelled, num_features = ndi.measurements.label(image[:, :, 0]) # find the objects slices = [] for obj in ndi.find_objects(labelled): if mask[obj[0], obj[1]].mean() <= 0.2: # remove letter holes (in o,e,a, etc.) continue if image[obj[0], obj[1]].size <= size_threshold: # remove very small slices continue slices.append(obj) indexed_slices = sorted(enumerate(slices), key=lambda slice: slice[1][1].start) letters = [] for i, (sy, sx) in indexed_slices: # crop each letter separately sy = slice(sy.start - 1, sy.stop + 1) sx = slice(sx.start - 1, sx.stop + 1) letter = image[sy, sx] labletter = labelled[sy, sx] maskletter = (labletter == (i + 1)) * mask[sy, sx] letter = ImageClip(image[sy, sx]) letter.mask = ImageClip(maskletter, is_mask=True) letter.screenpos = np.array((sx.start, sy.start)) letters.append(letter) if preview: # pragma: no cover import matplotlib.pyplot as plt print(f"Found {num_features} objects") fig, ax = plt.subplots(2) ax[0].axis("off") ax[0].imshow(labelled) ax[1].imshow([range(num_features)], interpolation="nearest") ax[1].set_yticks([]) plt.show() return letters
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/segmenting.py#L9-L81
46
[]
0
[ 0, 29, 33, 34, 37, 38, 39, 41, 42, 44, 45, 46, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 72 ]
38.709677
false
7.407407
73
7
61.290323
27
def find_objects(clip, size_threshold=500, preview=False): image = clip.get_frame(0) if not clip.mask: # pragma: no cover clip = clip.add_mask() mask = clip.mask.get_frame(0) labelled, num_features = ndi.measurements.label(image[:, :, 0]) # find the objects slices = [] for obj in ndi.find_objects(labelled): if mask[obj[0], obj[1]].mean() <= 0.2: # remove letter holes (in o,e,a, etc.) continue if image[obj[0], obj[1]].size <= size_threshold: # remove very small slices continue slices.append(obj) indexed_slices = sorted(enumerate(slices), key=lambda slice: slice[1][1].start) letters = [] for i, (sy, sx) in indexed_slices: # crop each letter separately sy = slice(sy.start - 1, sy.stop + 1) sx = slice(sx.start - 1, sx.stop + 1) letter = image[sy, sx] labletter = labelled[sy, sx] maskletter = (labletter == (i + 1)) * mask[sy, sx] letter = ImageClip(image[sy, sx]) letter.mask = ImageClip(maskletter, is_mask=True) letter.screenpos = np.array((sx.start, sy.start)) letters.append(letter) if preview: # pragma: no cover import matplotlib.pyplot as plt print(f"Found {num_features} objects") fig, ax = plt.subplots(2) ax[0].axis("off") ax[0].imshow(labelled) ax[1].imshow([range(num_features)], interpolation="nearest") ax[1].set_yticks([]) plt.show() return letters
28,473
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Interpolator.__init__
(self, tt=None, ss=None, ttss=None, left=None, right=None)
40
49
def __init__(self, tt=None, ss=None, ttss=None, left=None, right=None): if ttss is not None: tt, ss = zip(*ttss) self.tt = 1.0 * np.array(tt) self.ss = 1.0 * np.array(ss) self.left = left self.right = right self.tmin, self.tmax = min(tt), max(tt)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L40-L49
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
100
10
2
100
0
def __init__(self, tt=None, ss=None, ttss=None, left=None, right=None): if ttss is not None: tt, ss = zip(*ttss) self.tt = 1.0 * np.array(tt) self.ss = 1.0 * np.array(ss) self.left = left self.right = right self.tmin, self.tmax = min(tt), max(tt)
28,474
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Interpolator.__call__
(self, t)
return np.interp(t, self.tt, self.ss, self.left, self.right)
Interpolates ``t``. Parameters ---------- t : float Time frame for which the correspondent value will be returned.
Interpolates ``t``.
51
60
def __call__(self, t): """Interpolates ``t``. Parameters ---------- t : float Time frame for which the correspondent value will be returned. """ return np.interp(t, self.tt, self.ss, self.left, self.right)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L51-L60
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
100
10
1
100
7
def __call__(self, t): return np.interp(t, self.tt, self.ss, self.left, self.right)
28,475
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.__init__
(self, tt, xx, yy)
90
95
def __init__(self, tt, xx, yy): self.tt = 1.0 * np.array(tt) self.xx = np.array(xx) self.yy = np.array(yy) self.update_interpolators()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L90-L95
46
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
100
6
1
100
0
def __init__(self, tt, xx, yy): self.tt = 1.0 * np.array(tt) self.xx = np.array(xx) self.yy = np.array(yy) self.update_interpolators()
28,476
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.__call__
(self, t)
return np.array([self.xi(t), self.yi(t)])
Interpolates the trajectory at the given time ``t``. Parameters ---------- t : float Time for which to the corresponding position will be returned.
Interpolates the trajectory at the given time ``t``.
97
106
def __call__(self, t): """Interpolates the trajectory at the given time ``t``. Parameters ---------- t : float Time for which to the corresponding position will be returned. """ return np.array([self.xi(t), self.yi(t)])
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L97-L106
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
100
10
1
100
7
def __call__(self, t): return np.array([self.xi(t), self.yi(t)])
28,477
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.addx
(self, x)
return Trajectory(self.tt, self.xx + x, self.yy)
Adds a value to the ``xx`` position of the trajectory. Parameters ---------- x : int Value added to ``xx`` in the trajectory. Returns ------- Trajectory : new instance with the new X position included.
Adds a value to the ``xx`` position of the trajectory.
108
123
def addx(self, x): """Adds a value to the ``xx`` position of the trajectory. Parameters ---------- x : int Value added to ``xx`` in the trajectory. Returns ------- Trajectory : new instance with the new X position included. """ return Trajectory(self.tt, self.xx + x, self.yy)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L108-L123
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
100
16
1
100
13
def addx(self, x): return Trajectory(self.tt, self.xx + x, self.yy)
28,478
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.addy
(self, y)
return Trajectory(self.tt, self.xx, self.yy + y)
Adds a value to the ``yy`` position of the trajectory. Parameters ---------- y : int Value added to ``yy`` in the trajectory. Returns ------- Trajectory : new instance with the new Y position included.
Adds a value to the ``yy`` position of the trajectory.
125
140
def addy(self, y): """Adds a value to the ``yy`` position of the trajectory. Parameters ---------- y : int Value added to ``yy`` in the trajectory. Returns ------- Trajectory : new instance with the new Y position included. """ return Trajectory(self.tt, self.xx, self.yy + y)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L125-L140
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
100
[]
0
true
100
16
1
100
13
def addy(self, y): return Trajectory(self.tt, self.xx, self.yy + y)
28,479
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.update_interpolators
(self)
Updates the internal X and Y position interpolators for the instance.
Updates the internal X and Y position interpolators for the instance.
142
145
def update_interpolators(self): """Updates the internal X and Y position interpolators for the instance.""" self.xi = Interpolator(self.tt, self.xx) self.yi = Interpolator(self.tt, self.yy)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L142-L145
46
[ 0, 1, 2, 3 ]
100
[]
0
true
100
4
1
100
1
def update_interpolators(self): self.xi = Interpolator(self.tt, self.xx) self.yi = Interpolator(self.tt, self.yy)
28,480
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.txy
(self, tms=False)
return zip((1000 if tms else 1) * self.tt, self.xx, self.yy)
Returns all times with the X and Y values of each position. Parameters ---------- tms : bool, optional If is ``True``, the time will be returned in milliseconds.
Returns all times with the X and Y values of each position.
147
156
def txy(self, tms=False): """Returns all times with the X and Y values of each position. Parameters ---------- tms : bool, optional If is ``True``, the time will be returned in milliseconds. """ return zip((1000 if tms else 1) * self.tt, self.xx, self.yy)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L147-L156
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
100
10
1
100
7
def txy(self, tms=False): return zip((1000 if tms else 1) * self.tt, self.xx, self.yy)
28,481
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.to_file
(self, filename)
Saves the trajectory data in a text file. Parameters ---------- filename : str Path to the location of the new trajectory text file.
Saves the trajectory data in a text file.
158
172
def to_file(self, filename): """Saves the trajectory data in a text file. Parameters ---------- filename : str Path to the location of the new trajectory text file. """ np.savetxt( filename, np.array(list(self.txy(tms=True))), fmt="%d", delimiter="\t", )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L158-L172
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
100
[]
0
true
100
15
1
100
7
def to_file(self, filename): np.savetxt( filename, np.array(list(self.txy(tms=True))), fmt="%d", delimiter="\t", )
28,482
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.from_file
(filename)
return Trajectory(1.0 * tt / 1000, xx, yy)
Instantiates an object of Trajectory using a data text file. Parameters ---------- filename : str Path to the location of trajectory text file to load. Returns ------- Trajectory : new instance loaded from text file.
Instantiates an object of Trajectory using a data text file.
175
192
def from_file(filename): """Instantiates an object of Trajectory using a data text file. Parameters ---------- filename : str Path to the location of trajectory text file to load. Returns ------- Trajectory : new instance loaded from text file. """ arr = np.loadtxt(filename, delimiter="\t") tt, xx, yy = arr.T return Trajectory(1.0 * tt / 1000, xx, yy)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L175-L192
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
100
18
1
100
13
def from_file(filename): arr = np.loadtxt(filename, delimiter="\t") tt, xx, yy = arr.T return Trajectory(1.0 * tt / 1000, xx, yy)
28,483
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.save_list
(trajs, filename)
Saves a set of trajectories into a text file. Parameters ---------- trajs : list List of trajectories to be saved. filename : str Path of the text file that will store the trajectories data.
Saves a set of trajectories into a text file.
195
215
def save_list(trajs, filename): """Saves a set of trajectories into a text file. Parameters ---------- trajs : list List of trajectories to be saved. filename : str Path of the text file that will store the trajectories data. """ N = len(trajs) arr = np.hstack([np.array(list(t.txy(tms=True))) for t in trajs]) np.savetxt( filename, arr, fmt="%d", delimiter="\t", header="\t".join(N * ["t(ms)", "x", "y"]), )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L195-L215
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
100
21
2
100
10
def save_list(trajs, filename): N = len(trajs) arr = np.hstack([np.array(list(t.txy(tms=True))) for t in trajs]) np.savetxt( filename, arr, fmt="%d", delimiter="\t", header="\t".join(N * ["t(ms)", "x", "y"]), )
28,484
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/interpolators.py
Trajectory.load_list
(filename)
return [ Trajectory(tt=1.0 * a[0] / 1000, xx=a[1], yy=a[2]) for a in np.split(arr, Nlines / 3) ]
Loads a list of trajectories from a data text file. Parameters ---------- filename : str Path of the text file that stores the data of a set of trajectories. Returns ------- list : List of trajectories loaded from the file.
Loads a list of trajectories from a data text file.
218
238
def load_list(filename): """Loads a list of trajectories from a data text file. Parameters ---------- filename : str Path of the text file that stores the data of a set of trajectories. Returns ------- list : List of trajectories loaded from the file. """ arr = np.loadtxt(filename, delimiter="\t").T Nlines = arr.shape[0] return [ Trajectory(tt=1.0 * a[0] / 1000, xx=a[1], yy=a[2]) for a in np.split(arr, Nlines / 3) ]
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/interpolators.py#L218-L238
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
100
[]
0
true
100
21
2
100
13
def load_list(filename): arr = np.loadtxt(filename, delimiter="\t").T Nlines = arr.shape[0] return [ Trajectory(tt=1.0 * a[0] / 1000, xx=a[1], yy=a[2]) for a in np.split(arr, Nlines / 3) ]
28,485
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/tracking.py
manual_tracking
(clip, t1=None, t2=None, fps=None, n_objects=1, savefile=None)
return result
Manual tracking of objects in videoclips using the mouse. Allows manual tracking of an object(s) in the video clip between times `t1` and `t2`. This displays the clip frame by frame and you must click on the object(s) in each frame. If ``t2=None`` only the frame at ``t1`` is taken into account. Returns a list ``[(t1, x1, y1), (t2, x2, y2)...]`` if there is one object per frame, else returns a list whose elements are of the form ``(ti, [(xi1, yi1), (xi2, yi2)...])``. Parameters ---------- clip : video.VideoClip.VideoClip MoviePy video clip to track. t1 : float or str or tuple, optional Start time to to track (defaults is start of the clip). Can be expressed in seconds like ``15.35``, in ``(min, sec)``, in ``(hour, min, sec)``, or as a string: ``"01:03:05.35"``. t2 : float or str or tuple, optional End time to to track (defaults is end of the clip). Can be expressed in seconds like ``15.35``, in ``(min, sec)``, in ``(hour, min, sec)``, or as a string: ``"01:03:05.35"``. fps : int, optional Number of frames per second to freeze on. If None, the clip's fps attribute is used instead. n_objects : int, optional Number of objects to click on each frame. savefile : str, optional If provided, the result is saved to a file, which makes it easier to edit and re-use later. Examples -------- >>> from moviepy import VideoFileClip >>> from moviepy.video.tools.tracking import manual_tracking >>> >>> clip = VideoFileClip("media/chaplin.mp4") >>> >>> # manually indicate 3 trajectories, save them to a file >>> trajectories = manual_tracking(clip, start_time=5, t2=7, fps=5, ... nobjects=3, savefile="track.text") >>> >>> # ... >>> # later, in another script, recover these trajectories >>> from moviepy.video.tools.tracking import Trajectory >>> >>> traj1, traj2, traj3 = Trajectory.load_list('track.text') >>> >>> # If ever you only have one object being tracked, recover it with >>> traj, = Trajectory.load_list('track.text')
Manual tracking of objects in videoclips using the mouse.
29
143
def manual_tracking(clip, t1=None, t2=None, fps=None, n_objects=1, savefile=None): """Manual tracking of objects in videoclips using the mouse. Allows manual tracking of an object(s) in the video clip between times `t1` and `t2`. This displays the clip frame by frame and you must click on the object(s) in each frame. If ``t2=None`` only the frame at ``t1`` is taken into account. Returns a list ``[(t1, x1, y1), (t2, x2, y2)...]`` if there is one object per frame, else returns a list whose elements are of the form ``(ti, [(xi1, yi1), (xi2, yi2)...])``. Parameters ---------- clip : video.VideoClip.VideoClip MoviePy video clip to track. t1 : float or str or tuple, optional Start time to to track (defaults is start of the clip). Can be expressed in seconds like ``15.35``, in ``(min, sec)``, in ``(hour, min, sec)``, or as a string: ``"01:03:05.35"``. t2 : float or str or tuple, optional End time to to track (defaults is end of the clip). Can be expressed in seconds like ``15.35``, in ``(min, sec)``, in ``(hour, min, sec)``, or as a string: ``"01:03:05.35"``. fps : int, optional Number of frames per second to freeze on. If None, the clip's fps attribute is used instead. n_objects : int, optional Number of objects to click on each frame. savefile : str, optional If provided, the result is saved to a file, which makes it easier to edit and re-use later. Examples -------- >>> from moviepy import VideoFileClip >>> from moviepy.video.tools.tracking import manual_tracking >>> >>> clip = VideoFileClip("media/chaplin.mp4") >>> >>> # manually indicate 3 trajectories, save them to a file >>> trajectories = manual_tracking(clip, start_time=5, t2=7, fps=5, ... nobjects=3, savefile="track.text") >>> >>> # ... >>> # later, in another script, recover these trajectories >>> from moviepy.video.tools.tracking import Trajectory >>> >>> traj1, traj2, traj3 = Trajectory.load_list('track.text') >>> >>> # If ever you only have one object being tracked, recover it with >>> traj, = Trajectory.load_list('track.text') """ import pygame as pg screen = pg.display.set_mode(clip.size) step = 1.0 / fps if (t1 is None) and (t2 is None): t1, t2 = 0, clip.duration elif t2 is None: t2 = t1 + step / 2 t = t1 txy_list = [] def gatherClicks(t): imdisplay(clip.get_frame(t), screen) objects_to_click = n_objects clicks = [] while objects_to_click: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_BACKSLASH: return "return" elif event.key == pg.K_ESCAPE: raise KeyboardInterrupt() elif event.type == pg.MOUSEBUTTONDOWN: x, y = pg.mouse.get_pos() clicks.append((x, y)) objects_to_click -= 1 return clicks while t < t2: clicks = gatherClicks(t) if clicks == "return": txy_list.pop() t -= step else: txy_list.append((t, clicks)) t += step tt, xylist = zip(*txy_list) result = [] for i in range(n_objects): xys = [e[i] for e in xylist] xx, yy = zip(*xys) result.append(Trajectory(tt, xx, yy)) if savefile is not None: Trajectory.save_list(result, savefile) return result
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/tracking.py#L29-L143
46
[]
0
[ 0, 62, 64, 65, 66, 67, 68, 69, 70, 71, 73, 75, 76, 77, 78, 80, 82, 83, 84, 85, 86, 88, 89, 90, 91, 93, 95, 97, 98, 99, 100, 102, 103, 105, 106, 107, 108, 109, 110, 112, 113, 114 ]
36.521739
false
4.109589
115
16
63.478261
60
def manual_tracking(clip, t1=None, t2=None, fps=None, n_objects=1, savefile=None): import pygame as pg screen = pg.display.set_mode(clip.size) step = 1.0 / fps if (t1 is None) and (t2 is None): t1, t2 = 0, clip.duration elif t2 is None: t2 = t1 + step / 2 t = t1 txy_list = [] def gatherClicks(t): imdisplay(clip.get_frame(t), screen) objects_to_click = n_objects clicks = [] while objects_to_click: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_BACKSLASH: return "return" elif event.key == pg.K_ESCAPE: raise KeyboardInterrupt() elif event.type == pg.MOUSEBUTTONDOWN: x, y = pg.mouse.get_pos() clicks.append((x, y)) objects_to_click -= 1 return clicks while t < t2: clicks = gatherClicks(t) if clicks == "return": txy_list.pop() t -= step else: txy_list.append((t, clicks)) t += step tt, xylist = zip(*txy_list) result = [] for i in range(n_objects): xys = [e[i] for e in xylist] xx, yy = zip(*xys) result.append(Trajectory(tt, xx, yy)) if savefile is not None: Trajectory.save_list(result, savefile) return result
28,486
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/tracking.py
findAround
(pic, pat, xy=None, r=None)
return (x - r + xf, y - r + yf) if (xy and r) else (xf, yf)
Find an image pattern in a picture optionally defining bounds to search. The image is found is ``pat`` is inside ``pic[x +/- r, y +/- r]``. Parameters ---------- pic : numpy.ndarray Image where the pattern will be searched. pat : numpy.ndarray Pattern to search inside the image. xy : tuple or list, optional Position to search for the pattern. Use it in combination with ``radius`` parameter to define the bounds of the search. If is ``None``, consider the whole picture. r : float, optional Radius used to define the bounds of the search when ``xy`` argument is defined.
Find an image pattern in a picture optionally defining bounds to search.
146
176
def findAround(pic, pat, xy=None, r=None): """Find an image pattern in a picture optionally defining bounds to search. The image is found is ``pat`` is inside ``pic[x +/- r, y +/- r]``. Parameters ---------- pic : numpy.ndarray Image where the pattern will be searched. pat : numpy.ndarray Pattern to search inside the image. xy : tuple or list, optional Position to search for the pattern. Use it in combination with ``radius`` parameter to define the bounds of the search. If is ``None``, consider the whole picture. r : float, optional Radius used to define the bounds of the search when ``xy`` argument is defined. """ if xy and r: h, w = pat.shape[:2] x, y = xy pic = pic[y - r : y + h + r, x - r : x + w + r] matches = cv2.matchTemplate(pat, pic, cv2.TM_CCOEFF_NORMED) yf, xf = np.unravel_index(matches.argmax(), matches.shape) return (x - r + xf, y - r + yf) if (xy and r) else (xf, yf)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/tracking.py#L146-L176
46
[]
0
[ 0, 23, 24, 25, 26, 28, 29, 30 ]
25.806452
false
4.109589
31
4
74.193548
21
def findAround(pic, pat, xy=None, r=None): if xy and r: h, w = pat.shape[:2] x, y = xy pic = pic[y - r : y + h + r, x - r : x + w + r] matches = cv2.matchTemplate(pat, pic, cv2.TM_CCOEFF_NORMED) yf, xf = np.unravel_index(matches.argmax(), matches.shape) return (x - r + xf, y - r + yf) if (xy and r) else (xf, yf)
28,487
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/tracking.py
autoTrack
(clip, pattern, tt=None, fps=None, radius=20, xy0=None)
return Trajectory(tt, xx, yy)
Tracks a given pattern (small image array) in a video clip. Returns ``[(x1, y1), (x2, y2)...]`` where ``(xi, yi)`` are the coordinates of the pattern in the clip on frame ``i``. To select the frames you can either specify a list of times with ``tt`` or select a frame rate with ``fps``. This algorithm assumes that the pattern's aspect does not vary much and that the distance between two occurrences of the pattern in two consecutive frames is smaller than ``radius`` (if you set ``radius`` to -1 the pattern will be searched in the whole screen at each frame). You can also provide the original position of the pattern with xy0. Parameters ---------- clip : video.VideoClip.VideoClip MoviePy video clip to track. pattern : numpy.ndarray Image to search inside the clip frames. tt : numpy.ndarray, optional Time frames used for auto tracking. As default is used the clip time frames according to its fps. fps : int, optional Overwrites fps value used computing time frames. As default, clip's fps. radius : int, optional Maximum radius to search looking for the pattern. Set to ``-1``, the pattern will be searched in the whole screen at each frame. xy0 : tuple or list, optional Original position of the pattern. If not provided, will be taken from the first tracked frame of the clip.
Tracks a given pattern (small image array) in a video clip.
179
235
def autoTrack(clip, pattern, tt=None, fps=None, radius=20, xy0=None): """Tracks a given pattern (small image array) in a video clip. Returns ``[(x1, y1), (x2, y2)...]`` where ``(xi, yi)`` are the coordinates of the pattern in the clip on frame ``i``. To select the frames you can either specify a list of times with ``tt`` or select a frame rate with ``fps``. This algorithm assumes that the pattern's aspect does not vary much and that the distance between two occurrences of the pattern in two consecutive frames is smaller than ``radius`` (if you set ``radius`` to -1 the pattern will be searched in the whole screen at each frame). You can also provide the original position of the pattern with xy0. Parameters ---------- clip : video.VideoClip.VideoClip MoviePy video clip to track. pattern : numpy.ndarray Image to search inside the clip frames. tt : numpy.ndarray, optional Time frames used for auto tracking. As default is used the clip time frames according to its fps. fps : int, optional Overwrites fps value used computing time frames. As default, clip's fps. radius : int, optional Maximum radius to search looking for the pattern. Set to ``-1``, the pattern will be searched in the whole screen at each frame. xy0 : tuple or list, optional Original position of the pattern. If not provided, will be taken from the first tracked frame of the clip. """ if not autotracking_possible: raise IOError( "Sorry, autotrack requires OpenCV for the moment. " "Install OpenCV (aka cv2) to use it." ) if not xy0: xy0 = findAround(clip.get_frame(tt[0]), pattern) if tt is None: tt = np.arange(0, clip.duration, 1.0 / fps) xys = [xy0] for t in tt[1:]: xys.append(findAround(clip.get_frame(t), pattern, xy=xys[-1], r=radius)) xx, yy = zip(*xys) return Trajectory(tt, xx, yy)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/tracking.py#L179-L235
46
[]
0
[ 0, 38, 39, 44, 45, 47, 48, 50, 51, 52, 54, 56 ]
21.052632
false
4.109589
57
5
78.947368
36
def autoTrack(clip, pattern, tt=None, fps=None, radius=20, xy0=None): if not autotracking_possible: raise IOError( "Sorry, autotrack requires OpenCV for the moment. " "Install OpenCV (aka cv2) to use it." ) if not xy0: xy0 = findAround(clip.get_frame(tt[0]), pattern) if tt is None: tt = np.arange(0, clip.duration, 1.0 / fps) xys = [xy0] for t in tt[1:]: xys.append(findAround(clip.get_frame(t), pattern, xy=xys[-1], r=radius)) xx, yy = zip(*xys) return Trajectory(tt, xx, yy)
28,488
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/drawing.py
blit
(im1, im2, pos=None, mask=None)
return im2
Blit an image over another. Blits ``im1`` on ``im2`` as position ``pos=(x,y)``, using the ``mask`` if provided.
Blit an image over another.
8
20
def blit(im1, im2, pos=None, mask=None): """Blit an image over another. Blits ``im1`` on ``im2`` as position ``pos=(x,y)``, using the ``mask`` if provided. """ if pos is None: pos = (0, 0) # pragma: no cover else: # Cast to tuple in case pos is not subscriptable. pos = tuple(pos) im2.paste(im1, pos, mask) return im2
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/drawing.py#L8-L20
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
108.333333
[]
0
true
100
13
2
100
4
def blit(im1, im2, pos=None, mask=None): if pos is None: pos = (0, 0) # pragma: no cover else: # Cast to tuple in case pos is not subscriptable. pos = tuple(pos) im2.paste(im1, pos, mask) return im2
28,489
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/drawing.py
color_gradient
( size, p1, p2=None, vector=None, radius=None, color_1=0.0, color_2=1.0, shape="linear", offset=0, )
Draw a linear, bilinear, or radial gradient. The result is a picture of size ``size``, whose color varies gradually from color `color_1` in position ``p1`` to color ``color_2`` in position ``p2``. If it is a RGB picture the result must be transformed into a 'uint8' array to be displayed normally: Parameters ---------- size : tuple or list Size (width, height) in pixels of the final image array. p1 : tuple or list Position for the first coordinate of the gradient in pixels (x, y). The color 'before' ``p1`` is ``color_1`` and it gradually changes in the direction of ``p2`` until it is ``color_2`` when it reaches ``p2``. p2 : tuple or list, optional Position for the second coordinate of the gradient in pixels (x, y). Coordinates (x, y) of the limit point for ``color_1`` and ``color_2``. vector : tuple or list, optional A vector (x, y) in pixels that can be provided instead of ``p2``. ``p2`` is then defined as (p1 + vector). color_1 : tuple or list, optional Starting color for the gradient. As default, black. Either floats between 0 and 1 (for gradients used in masks) or [R, G, B] arrays (for colored gradients). color_2 : tuple or list, optional Color for the second point in the gradient. As default, white. Either floats between 0 and 1 (for gradients used in masks) or [R, G, B] arrays (for colored gradients). shape : str, optional Shape of the gradient. Can be either ``"linear"``, ``"bilinear"`` or ``"circular"``. In a linear gradient the color varies in one direction, from point ``p1`` to point ``p2``. In a bilinear gradient it also varies symmetrically from ``p1`` in the other direction. In a circular gradient it goes from ``color_1`` to ``color_2`` in all directions. radius : float, optional If ``shape="radial"``, the radius of the gradient is defined with the parameter ``radius``, in pixels. offset : float, optional Real number between 0 and 1 indicating the fraction of the vector at which the gradient actually starts. For instance if ``offset`` is 0.9 in a gradient going from p1 to p2, then the gradient will only occur near p2 (before that everything is of color ``color_1``) If the offset is 0.9 in a radial gradient, the gradient will occur in the region located between 90% and 100% of the radius, this creates a blurry disc of radius ``d(p1, p2)``. Returns ------- image An Numpy array of dimensions (width, height, n_colors) of type float representing the image of the gradient. Examples -------- >>> color_gradient((10, 1), (0, 0), p2=(10, 0)) # from white to black [[1. 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1]] >>> >>> color_gradient( # from red to green ... (10, 1), # size ... (0, 0), # p1 ... p2=(10, 0), ... color_1=(255, 0, 0), # red ... color_2=(0, 255, 0), # green ... ) [[[ 0. 255. 0. ] [ 25.5 229.5 0. ] [ 51. 204. 0. ] [ 76.5 178.5 0. ] [102. 153. 0. ] [127.5 127.5 0. ] [153. 102. 0. ] [178.5 76.5 0. ] [204. 51. 0. ] [229.5 25.5 0. ]]]
Draw a linear, bilinear, or radial gradient.
23
188
def color_gradient( size, p1, p2=None, vector=None, radius=None, color_1=0.0, color_2=1.0, shape="linear", offset=0, ): """Draw a linear, bilinear, or radial gradient. The result is a picture of size ``size``, whose color varies gradually from color `color_1` in position ``p1`` to color ``color_2`` in position ``p2``. If it is a RGB picture the result must be transformed into a 'uint8' array to be displayed normally: Parameters ---------- size : tuple or list Size (width, height) in pixels of the final image array. p1 : tuple or list Position for the first coordinate of the gradient in pixels (x, y). The color 'before' ``p1`` is ``color_1`` and it gradually changes in the direction of ``p2`` until it is ``color_2`` when it reaches ``p2``. p2 : tuple or list, optional Position for the second coordinate of the gradient in pixels (x, y). Coordinates (x, y) of the limit point for ``color_1`` and ``color_2``. vector : tuple or list, optional A vector (x, y) in pixels that can be provided instead of ``p2``. ``p2`` is then defined as (p1 + vector). color_1 : tuple or list, optional Starting color for the gradient. As default, black. Either floats between 0 and 1 (for gradients used in masks) or [R, G, B] arrays (for colored gradients). color_2 : tuple or list, optional Color for the second point in the gradient. As default, white. Either floats between 0 and 1 (for gradients used in masks) or [R, G, B] arrays (for colored gradients). shape : str, optional Shape of the gradient. Can be either ``"linear"``, ``"bilinear"`` or ``"circular"``. In a linear gradient the color varies in one direction, from point ``p1`` to point ``p2``. In a bilinear gradient it also varies symmetrically from ``p1`` in the other direction. In a circular gradient it goes from ``color_1`` to ``color_2`` in all directions. radius : float, optional If ``shape="radial"``, the radius of the gradient is defined with the parameter ``radius``, in pixels. offset : float, optional Real number between 0 and 1 indicating the fraction of the vector at which the gradient actually starts. For instance if ``offset`` is 0.9 in a gradient going from p1 to p2, then the gradient will only occur near p2 (before that everything is of color ``color_1``) If the offset is 0.9 in a radial gradient, the gradient will occur in the region located between 90% and 100% of the radius, this creates a blurry disc of radius ``d(p1, p2)``. Returns ------- image An Numpy array of dimensions (width, height, n_colors) of type float representing the image of the gradient. Examples -------- >>> color_gradient((10, 1), (0, 0), p2=(10, 0)) # from white to black [[1. 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1]] >>> >>> color_gradient( # from red to green ... (10, 1), # size ... (0, 0), # p1 ... p2=(10, 0), ... color_1=(255, 0, 0), # red ... color_2=(0, 255, 0), # green ... ) [[[ 0. 255. 0. ] [ 25.5 229.5 0. ] [ 51. 204. 0. ] [ 76.5 178.5 0. ] [102. 153. 0. ] [127.5 127.5 0. ] [153. 102. 0. ] [178.5 76.5 0. ] [204. 51. 0. ] [229.5 25.5 0. ]]] """ # np-arrayize and change x,y coordinates to y,x w, h = size color_1 = np.array(color_1).astype(float) color_2 = np.array(color_2).astype(float) if shape == "bilinear": if vector is None: if p2 is None: raise ValueError("You must provide either 'p2' or 'vector'") vector = np.array(p2) - np.array(p1) m1, m2 = [ color_gradient( size, p1, vector=v, color_1=1.0, color_2=0.0, shape="linear", offset=offset, ) for v in [vector, [-v for v in vector]] ] arr = np.maximum(m1, m2) if color_1.size > 1: arr = np.dstack(3 * [arr]) return arr * color_1 + (1 - arr) * color_2 p1 = np.array(p1[::-1]).astype(float) M = np.dstack(np.meshgrid(range(w), range(h))[::-1]).astype(float) if shape == "linear": if vector is None: if p2 is not None: vector = np.array(p2[::-1]) - p1 else: raise ValueError("You must provide either 'p2' or 'vector'") else: vector = np.array(vector[::-1]) norm = np.linalg.norm(vector) n_vec = vector / norm**2 # norm 1/norm(vector) p1 = p1 + offset * vector arr = (M - p1).dot(n_vec) / (1 - offset) arr = np.minimum(1, np.maximum(0, arr)) if color_1.size > 1: arr = np.dstack(3 * [arr]) return arr * color_1 + (1 - arr) * color_2 elif shape == "radial": if (radius or 0) == 0: arr = np.ones((h, w)) else: arr = (np.sqrt(((M - p1) ** 2).sum(axis=2))) - offset * radius arr = arr / ((1 - offset) * radius) arr = np.minimum(1.0, np.maximum(0, arr)) if color_1.size > 1: arr = np.dstack(3 * [arr]) return (1 - arr) * color_1 + arr * color_2 raise ValueError("Invalid shape, should be either 'radial', 'linear' or 'bilinear'")
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/drawing.py#L23-L188
46
[ 0, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 140, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 158, 159, 160, 161, 162, 163, 164, 165 ]
31.325301
[]
0
false
100
166
15
100
89
def color_gradient( size, p1, p2=None, vector=None, radius=None, color_1=0.0, color_2=1.0, shape="linear", offset=0, ): # np-arrayize and change x,y coordinates to y,x w, h = size color_1 = np.array(color_1).astype(float) color_2 = np.array(color_2).astype(float) if shape == "bilinear": if vector is None: if p2 is None: raise ValueError("You must provide either 'p2' or 'vector'") vector = np.array(p2) - np.array(p1) m1, m2 = [ color_gradient( size, p1, vector=v, color_1=1.0, color_2=0.0, shape="linear", offset=offset, ) for v in [vector, [-v for v in vector]] ] arr = np.maximum(m1, m2) if color_1.size > 1: arr = np.dstack(3 * [arr]) return arr * color_1 + (1 - arr) * color_2 p1 = np.array(p1[::-1]).astype(float) M = np.dstack(np.meshgrid(range(w), range(h))[::-1]).astype(float) if shape == "linear": if vector is None: if p2 is not None: vector = np.array(p2[::-1]) - p1 else: raise ValueError("You must provide either 'p2' or 'vector'") else: vector = np.array(vector[::-1]) norm = np.linalg.norm(vector) n_vec = vector / norm**2 # norm 1/norm(vector) p1 = p1 + offset * vector arr = (M - p1).dot(n_vec) / (1 - offset) arr = np.minimum(1, np.maximum(0, arr)) if color_1.size > 1: arr = np.dstack(3 * [arr]) return arr * color_1 + (1 - arr) * color_2 elif shape == "radial": if (radius or 0) == 0: arr = np.ones((h, w)) else: arr = (np.sqrt(((M - p1) ** 2).sum(axis=2))) - offset * radius arr = arr / ((1 - offset) * radius) arr = np.minimum(1.0, np.maximum(0, arr)) if color_1.size > 1: arr = np.dstack(3 * [arr]) return (1 - arr) * color_1 + arr * color_2 raise ValueError("Invalid shape, should be either 'radial', 'linear' or 'bilinear'")
28,490
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/drawing.py
color_split
( size, x=None, y=None, p1=None, p2=None, vector=None, color_1=0, color_2=1.0, gradient_width=0, )
Make an image split in 2 colored regions. Returns an array of size ``size`` divided in two regions called 1 and 2 in what follows, and which will have colors color_1 and color_2 respectively. Parameters ---------- x : int, optional If provided, the image is split horizontally in x, the left region being region 1. y : int, optional If provided, the image is split vertically in y, the top region being region 1. p1, p2: tuple or list, optional Positions (x1, y1), (x2, y2) in pixels, where the numbers can be floats. Region 1 is defined as the whole region on the left when going from ``p1`` to ``p2``. p1, vector: tuple or list, optional ``p1`` is (x1,y1) and vector (v1,v2), where the numbers can be floats. Region 1 is then the region on the left when starting in position ``p1`` and going in the direction given by ``vector``. gradient_width : float, optional If not zero, the split is not sharp, but gradual over a region of width ``gradient_width`` (in pixels). This is preferable in many situations (for instance for antialiasing). Examples -------- >>> size = [200, 200] >>> >>> # an image with all pixels with x<50 =0, the others =1 >>> color_split(size, x=50, color_1=0, color_2=1) >>> >>> # an image with all pixels with y<50 red, the others green >>> color_split(size, x=50, color_1=[255, 0, 0], color_2=[0, 255, 0]) >>> >>> # An image split along an arbitrary line (see below) >>> color_split(size, p1=[20, 50], p2=[25, 70] color_1=0, color_2=1)
Make an image split in 2 colored regions.
191
275
def color_split( size, x=None, y=None, p1=None, p2=None, vector=None, color_1=0, color_2=1.0, gradient_width=0, ): """Make an image split in 2 colored regions. Returns an array of size ``size`` divided in two regions called 1 and 2 in what follows, and which will have colors color_1 and color_2 respectively. Parameters ---------- x : int, optional If provided, the image is split horizontally in x, the left region being region 1. y : int, optional If provided, the image is split vertically in y, the top region being region 1. p1, p2: tuple or list, optional Positions (x1, y1), (x2, y2) in pixels, where the numbers can be floats. Region 1 is defined as the whole region on the left when going from ``p1`` to ``p2``. p1, vector: tuple or list, optional ``p1`` is (x1,y1) and vector (v1,v2), where the numbers can be floats. Region 1 is then the region on the left when starting in position ``p1`` and going in the direction given by ``vector``. gradient_width : float, optional If not zero, the split is not sharp, but gradual over a region of width ``gradient_width`` (in pixels). This is preferable in many situations (for instance for antialiasing). Examples -------- >>> size = [200, 200] >>> >>> # an image with all pixels with x<50 =0, the others =1 >>> color_split(size, x=50, color_1=0, color_2=1) >>> >>> # an image with all pixels with y<50 red, the others green >>> color_split(size, x=50, color_1=[255, 0, 0], color_2=[0, 255, 0]) >>> >>> # An image split along an arbitrary line (see below) >>> color_split(size, p1=[20, 50], p2=[25, 70] color_1=0, color_2=1) """ if gradient_width or ((x is None) and (y is None)): if p2 is not None: vector = np.array(p2) - np.array(p1) elif x is not None: vector = np.array([0, -1.0]) p1 = np.array([x, 0]) elif y is not None: vector = np.array([1.0, 0.0]) p1 = np.array([0, y]) x, y = vector vector = np.array([y, -x]).astype("float") norm = np.linalg.norm(vector) vector = max(0.1, gradient_width) * vector / norm return color_gradient( size, p1, vector=vector, color_1=color_1, color_2=color_2, shape="linear" ) else: w, h = size shape = (h, w) if np.isscalar(color_1) else (h, w, len(color_1)) arr = np.zeros(shape) if x: arr[:, :x] = color_1 arr[:, x:] = color_2 elif y: arr[:y] = color_1 arr[y:] = color_2 return arr
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/drawing.py#L191-L275
46
[ 0, 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 ]
35.294118
[]
0
false
100
85
9
100
45
def color_split( size, x=None, y=None, p1=None, p2=None, vector=None, color_1=0, color_2=1.0, gradient_width=0, ): if gradient_width or ((x is None) and (y is None)): if p2 is not None: vector = np.array(p2) - np.array(p1) elif x is not None: vector = np.array([0, -1.0]) p1 = np.array([x, 0]) elif y is not None: vector = np.array([1.0, 0.0]) p1 = np.array([0, y]) x, y = vector vector = np.array([y, -x]).astype("float") norm = np.linalg.norm(vector) vector = max(0.1, gradient_width) * vector / norm return color_gradient( size, p1, vector=vector, color_1=color_1, color_2=color_2, shape="linear" ) else: w, h = size shape = (h, w) if np.isscalar(color_1) else (h, w, len(color_1)) arr = np.zeros(shape) if x: arr[:, :x] = color_1 arr[:, x:] = color_2 elif y: arr[:y] = color_1 arr[y:] = color_2 return arr
28,491
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/drawing.py
circle
(screensize, center, radius, color=1.0, bg_color=0, blur=1)
return color_gradient( screensize, p1=center, radius=radius, color_1=color, color_2=bg_color, shape="radial", offset=offset, )
Draw an image with a circle. Draws a circle of color ``color``, on a background of color ``bg_color``, on a screen of size ``screensize`` at the position ``center=(x, y)``, with a radius ``radius`` but slightly blurred on the border by ``blur`` pixels. Parameters ---------- screensize : tuple or list Size of the canvas. center : tuple or list Center of the circle. radius : float Radius of the circle, in pixels. bg_color : tuple or float, optional Color for the background of the canvas. As default, black. blur : float, optional Blur for the border of the circle. Examples -------- >>> from moviepy.video.tools.drawing import circle >>> >>> circle( ... (5, 5), # size ... (2, 2), # center ... 2, # radius ... ) array([[0. , 0. , 0. , 0. , 0. ], [0. , 0.58578644, 1. , 0.58578644, 0. ], [0. , 1. , 1. , 1. , 0. ], [0. , 0.58578644, 1. , 0.58578644, 0. ], [0. , 0. , 0. , 0. , 0. ]])
Draw an image with a circle.
278
329
def circle(screensize, center, radius, color=1.0, bg_color=0, blur=1): """Draw an image with a circle. Draws a circle of color ``color``, on a background of color ``bg_color``, on a screen of size ``screensize`` at the position ``center=(x, y)``, with a radius ``radius`` but slightly blurred on the border by ``blur`` pixels. Parameters ---------- screensize : tuple or list Size of the canvas. center : tuple or list Center of the circle. radius : float Radius of the circle, in pixels. bg_color : tuple or float, optional Color for the background of the canvas. As default, black. blur : float, optional Blur for the border of the circle. Examples -------- >>> from moviepy.video.tools.drawing import circle >>> >>> circle( ... (5, 5), # size ... (2, 2), # center ... 2, # radius ... ) array([[0. , 0. , 0. , 0. , 0. ], [0. , 0.58578644, 1. , 0.58578644, 0. ], [0. , 1. , 1. , 1. , 0. ], [0. , 0.58578644, 1. , 0.58578644, 0. ], [0. , 0. , 0. , 0. , 0. ]]) """ offset = 1.0 * (radius - blur) / radius if radius else 0 return color_gradient( screensize, p1=center, radius=radius, color_1=color, color_2=bg_color, shape="radial", offset=offset, )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/drawing.py#L278-L329
46
[ 0, 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 ]
100
[]
0
true
100
52
1
100
40
def circle(screensize, center, radius, color=1.0, bg_color=0, blur=1): offset = 1.0 * (radius - blur) / radius if radius else 0 return color_gradient( screensize, p1=center, radius=radius, color_1=color, color_2=bg_color, shape="radial", offset=offset, )
28,492
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
file_to_subtitles
(filename, encoding=None)
return times_texts
Converts a srt file into subtitles. The returned list is of the form ``[((start_time,end_time),'some text'),...]`` and can be fed to SubtitlesClip. Only works for '.srt' format for the moment.
Converts a srt file into subtitles.
163
184
def file_to_subtitles(filename, encoding=None): """Converts a srt file into subtitles. The returned list is of the form ``[((start_time,end_time),'some text'),...]`` and can be fed to SubtitlesClip. Only works for '.srt' format for the moment. """ times_texts = [] current_times = None current_text = "" with open(filename, "r", encoding=encoding) as file: for line in file: times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line) if times: current_times = [convert_to_seconds(t) for t in times] elif line.strip() == "": times_texts.append((current_times, current_text.strip("\n"))) current_times, current_text = None, "" elif current_times: current_text += line return times_texts
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L163-L184
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
35.365854
22
7
100
6
def file_to_subtitles(filename, encoding=None): times_texts = [] current_times = None current_text = "" with open(filename, "r", encoding=encoding) as file: for line in file: times = re.findall("([0-9]*:[0-9]*:[0-9]*,[0-9]*)", line) if times: current_times = [convert_to_seconds(t) for t in times] elif line.strip() == "": times_texts.append((current_times, current_text.strip("\n"))) current_times, current_text = None, "" elif current_times: current_text += line return times_texts
28,493
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.__init__
(self, subtitles, make_textclip=None, encoding=None)
45
109
def __init__(self, subtitles, make_textclip=None, encoding=None): VideoClip.__init__(self, has_constant_size=False) if not isinstance(subtitles, list): # `subtitles` is a string or path-like object subtitles = file_to_subtitles(subtitles, encoding=encoding) # subtitles = [(map(convert_to_seconds, times), text) # for times, text in subtitles] self.subtitles = subtitles self.textclips = dict() if make_textclip is None: def make_textclip(txt): return TextClip( txt, font="Georgia-Bold", font_size=24, color="white", stroke_color="black", stroke_width=0.5, ) self.make_textclip = make_textclip self.start = 0 self.duration = max([tb for ((ta, tb), txt) in self.subtitles]) self.end = self.duration def add_textclip_if_none(t): """Will generate a textclip if it hasn't been generated asked to generate it yet. If there is no subtitle to show at t, return false. """ sub = [ ((text_start, text_end), text) for ((text_start, text_end), text) in self.textclips.keys() if (text_start <= t < text_end) ] if not sub: sub = [ ((text_start, text_end), text) for ((text_start, text_end), text) in self.subtitles if (text_start <= t < text_end) ] if not sub: return False sub = sub[0] if sub not in self.textclips.keys(): self.textclips[sub] = self.make_textclip(sub[1]) return sub def make_frame(t): sub = add_textclip_if_none(t) return self.textclips[sub].get_frame(t) if sub else np.array([[[0, 0, 0]]]) def make_mask_frame(t): sub = add_textclip_if_none(t) return self.textclips[sub].mask.get_frame(t) if sub else np.array([[0]]) self.make_frame = make_frame hasmask = bool(self.make_textclip("T").mask) self.mask = VideoClip(make_mask_frame, is_mask=True) if hasmask else None
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L45-L109
46
[ 0, 1 ]
3.076923
[ 2, 4, 6, 10, 11, 13, 15, 16, 25, 26, 27, 28, 30, 35, 40, 41, 46, 47, 48, 49, 50, 52, 54, 55, 56, 58, 59, 60, 62, 63, 64 ]
47.692308
false
35.365854
65
13
52.307692
0
def __init__(self, subtitles, make_textclip=None, encoding=None): VideoClip.__init__(self, has_constant_size=False) if not isinstance(subtitles, list): # `subtitles` is a string or path-like object subtitles = file_to_subtitles(subtitles, encoding=encoding) # subtitles = [(map(convert_to_seconds, times), text) # for times, text in subtitles] self.subtitles = subtitles self.textclips = dict() if make_textclip is None: def make_textclip(txt): return TextClip( txt, font="Georgia-Bold", font_size=24, color="white", stroke_color="black", stroke_width=0.5, ) self.make_textclip = make_textclip self.start = 0 self.duration = max([tb for ((ta, tb), txt) in self.subtitles]) self.end = self.duration def add_textclip_if_none(t): sub = [ ((text_start, text_end), text) for ((text_start, text_end), text) in self.textclips.keys() if (text_start <= t < text_end) ] if not sub: sub = [ ((text_start, text_end), text) for ((text_start, text_end), text) in self.subtitles if (text_start <= t < text_end) ] if not sub: return False sub = sub[0] if sub not in self.textclips.keys(): self.textclips[sub] = self.make_textclip(sub[1]) return sub def make_frame(t): sub = add_textclip_if_none(t) return self.textclips[sub].get_frame(t) if sub else np.array([[[0, 0, 0]]]) def make_mask_frame(t): sub = add_textclip_if_none(t) return self.textclips[sub].mask.get_frame(t) if sub else np.array([[0]]) self.make_frame = make_frame hasmask = bool(self.make_textclip("T").mask) self.mask = VideoClip(make_mask_frame, is_mask=True) if hasmask else None
28,494
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.in_subclip
(self, start_time=None, end_time=None)
return [ (try_cropping(t1, t2), txt) for ((t1, t2), txt) in self.subtitles if is_in_subclip(t1, t2) ]
Returns a sequence of [(t1,t2), text] covering all the given subclip from start_time to end_time. The first and last times will be cropped so as to be exactly start_time and end_time if possible.
Returns a sequence of [(t1,t2), text] covering all the given subclip from start_time to end_time. The first and last times will be cropped so as to be exactly start_time and end_time if possible.
111
133
def in_subclip(self, start_time=None, end_time=None): """Returns a sequence of [(t1,t2), text] covering all the given subclip from start_time to end_time. The first and last times will be cropped so as to be exactly start_time and end_time if possible. """ def is_in_subclip(t1, t2): try: return (start_time <= t1 < end_time) or (start_time < t2 <= end_time) except Exception: return False def try_cropping(t1, t2): try: return max(t1, start_time), min(t2, end_time) except Exception: return t1, t2 return [ (try_cropping(t1, t2), txt) for ((t1, t2), txt) in self.subtitles if is_in_subclip(t1, t2) ]
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L111-L133
46
[ 0, 1, 2, 3, 4, 5 ]
26.086957
[ 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18 ]
47.826087
false
35.365854
23
7
52.173913
3
def in_subclip(self, start_time=None, end_time=None): def is_in_subclip(t1, t2): try: return (start_time <= t1 < end_time) or (start_time < t2 <= end_time) except Exception: return False def try_cropping(t1, t2): try: return max(t1, start_time), min(t2, end_time) except Exception: return t1, t2 return [ (try_cropping(t1, t2), txt) for ((t1, t2), txt) in self.subtitles if is_in_subclip(t1, t2) ]
28,495
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.__iter__
(self)
return iter(self.subtitles)
135
136
def __iter__(self): return iter(self.subtitles)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L135-L136
46
[ 0 ]
50
[ 1 ]
50
false
35.365854
2
1
50
0
def __iter__(self): return iter(self.subtitles)
28,496
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.__getitem__
(self, k)
return self.subtitles[k]
138
139
def __getitem__(self, k): return self.subtitles[k]
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L138-L139
46
[ 0 ]
50
[ 1 ]
50
false
35.365854
2
1
50
0
def __getitem__(self, k): return self.subtitles[k]
28,497
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.__str__
(self)
return "\n\n".join(to_srt(sub) for sub in self.subtitles)
141
148
def __str__(self): def to_srt(sub_element): (start_time, end_time), text = sub_element formatted_start_time = convert_to_seconds(start_time) formatted_end_time = convert_to_seconds(end_time) return "%s - %s\n%s" % (formatted_start_time, formatted_end_time, text) return "\n\n".join(to_srt(sub) for sub in self.subtitles)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L141-L148
46
[ 0 ]
12.5
[ 1, 2, 3, 4, 5, 7 ]
75
false
35.365854
8
2
25
0
def __str__(self): def to_srt(sub_element): (start_time, end_time), text = sub_element formatted_start_time = convert_to_seconds(start_time) formatted_end_time = convert_to_seconds(end_time) return "%s - %s\n%s" % (formatted_start_time, formatted_end_time, text) return "\n\n".join(to_srt(sub) for sub in self.subtitles)
28,498
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.match_expr
(self, expr)
return SubtitlesClip( [sub for sub in self.subtitles if re.findall(expr, sub[1]) != []] )
Matches a regular expression against the subtitles of the clip.
Matches a regular expression against the subtitles of the clip.
150
154
def match_expr(self, expr): """Matches a regular expression against the subtitles of the clip.""" return SubtitlesClip( [sub for sub in self.subtitles if re.findall(expr, sub[1]) != []] )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L150-L154
46
[ 0, 1 ]
40
[ 2 ]
20
false
35.365854
5
2
80
1
def match_expr(self, expr): return SubtitlesClip( [sub for sub in self.subtitles if re.findall(expr, sub[1]) != []] )
28,499
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/subtitles.py
SubtitlesClip.write_srt
(self, filename)
Writes an ``.srt`` file with the content of the clip.
Writes an ``.srt`` file with the content of the clip.
156
159
def write_srt(self, filename): """Writes an ``.srt`` file with the content of the clip.""" with open(filename, "w+") as file: file.write(str(self))
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/subtitles.py#L156-L159
46
[ 0, 1 ]
50
[ 2, 3 ]
50
false
35.365854
4
2
50
1
def write_srt(self, filename): with open(filename, "w+") as file: file.write(str(self))
28,500
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/tools/credits.py
CreditsClip.__init__
( self, creditfile, width, stretch=30, color="white", stroke_color="black", stroke_width=2, font="Impact-Normal", font_size=60, bg_color=None, gap=0, )
77
141
def __init__( self, creditfile, width, stretch=30, color="white", stroke_color="black", stroke_width=2, font="Impact-Normal", font_size=60, bg_color=None, gap=0, ): # Parse the .txt file texts = [] one_line = True with open(creditfile) as file: for line in file: if line.startswith(("\n", "#")): # exclude blank lines or comments continue elif line.startswith(".blank"): # ..blank n for i in range(int(line.split(" ")[1])): texts.append(["\n", "\n"]) elif line.startswith(".."): texts.append([line[2:], ""]) one_line = True elif one_line: texts.append(["", line]) one_line = False else: texts.append(["\n", line]) left, right = ("".join(line) for line in zip(*texts)) # Make two columns for the credits left, right = [ TextClip( txt, color=color, stroke_color=stroke_color, stroke_width=stroke_width, font=font, font_size=font_size, align=align, ) for txt, align in [(left, "East"), (right, "West")] ] both_columns = CompositeVideoClip( [left, right.with_position((left.w + gap, 0))], size=(left.w + right.w + gap, right.h), bg_color=bg_color, ) # Scale to the required size scaled = resize(both_columns, width=width) # Transform the CompositeVideoClip into an ImageClip # Calls ImageClip.__init__() super(TextClip, self).__init__(scaled.get_frame(0)) self.mask = ImageClip(scaled.mask.get_frame(0), is_mask=True)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/tools/credits.py#L77-L141
46
[ 0 ]
1.538462
[ 14, 15, 17, 18, 19, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 33, 35, 38, 51, 58, 63, 64 ]
33.846154
false
24.137931
65
9
66.153846
0
def __init__( self, creditfile, width, stretch=30, color="white", stroke_color="black", stroke_width=2, font="Impact-Normal", font_size=60, bg_color=None, gap=0, ): # Parse the .txt file texts = [] one_line = True with open(creditfile) as file: for line in file: if line.startswith(("\n", "#")): # exclude blank lines or comments continue elif line.startswith(".blank"): # ..blank n for i in range(int(line.split(" ")[1])): texts.append(["\n", "\n"]) elif line.startswith(".."): texts.append([line[2:], ""]) one_line = True elif one_line: texts.append(["", line]) one_line = False else: texts.append(["\n", line]) left, right = ("".join(line) for line in zip(*texts)) # Make two columns for the credits left, right = [ TextClip( txt, color=color, stroke_color=stroke_color, stroke_width=stroke_width, font=font, font_size=font_size, align=align, ) for txt, align in [(left, "East"), (right, "West")] ] both_columns = CompositeVideoClip( [left, right.with_position((left.w + gap, 0))], size=(left.w + right.w + gap, right.h), bg_color=bg_color, ) # Scale to the required size scaled = resize(both_columns, width=width) # Transform the CompositeVideoClip into an ImageClip # Calls ImageClip.__init__() super(TextClip, self).__init__(scaled.get_frame(0)) self.mask = ImageClip(scaled.mask.get_frame(0), is_mask=True)
28,501
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
ffmpeg_read_image
(filename, with_mask=True, pixel_format=None)
return im
Read an image file (PNG, BMP, JPEG...). Wraps FFMPEG_Videoreader to read just one image. Returns an ImageClip. This function is not meant to be used directly in MoviePy. Use ImageClip instead to make clips out of image files. Parameters ---------- filename Name of the image file. Can be of any format supported by ffmpeg. with_mask If the image has a transparency layer, ``with_mask=true`` will save this layer as the mask of the returned ImageClip pixel_format Optional: Pixel format for the image to read. If is not specified 'rgb24' will be used as the default format unless ``with_mask`` is set as ``True``, then 'rgba' will be used.
Read an image file (PNG, BMP, JPEG...).
253
285
def ffmpeg_read_image(filename, with_mask=True, pixel_format=None): """Read an image file (PNG, BMP, JPEG...). Wraps FFMPEG_Videoreader to read just one image. Returns an ImageClip. This function is not meant to be used directly in MoviePy. Use ImageClip instead to make clips out of image files. Parameters ---------- filename Name of the image file. Can be of any format supported by ffmpeg. with_mask If the image has a transparency layer, ``with_mask=true`` will save this layer as the mask of the returned ImageClip pixel_format Optional: Pixel format for the image to read. If is not specified 'rgb24' will be used as the default format unless ``with_mask`` is set as ``True``, then 'rgba' will be used. """ if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" reader = FFMPEG_VideoReader( filename, pixel_format=pixel_format, check_duration=False ) im = reader.last_read del reader return im
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L253-L285
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
75.757576
[ 25, 26, 27, 30, 31, 32 ]
18.181818
false
89.814815
33
2
81.818182
22
def ffmpeg_read_image(filename, with_mask=True, pixel_format=None): if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" reader = FFMPEG_VideoReader( filename, pixel_format=pixel_format, check_duration=False ) im = reader.last_read del reader return im
28,502
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
ffmpeg_parse_infos
( filename, check_duration=True, fps_source="fps", decode_file=False, print_infos=False, )
Get the information of a file using ffmpeg. Returns a dictionary with next fields: - ``"duration"`` - ``"metadata"`` - ``"inputs"`` - ``"video_found"`` - ``"video_fps"`` - ``"video_n_frames"`` - ``"video_duration"`` - ``"video_bitrate"`` - ``"video_metadata"`` - ``"audio_found"`` - ``"audio_fps"`` - ``"audio_bitrate"`` - ``"audio_metadata"`` Note that "video_duration" is slightly smaller than "duration" to avoid fetching the incomplete frames at the end, which raises an error. Parameters ---------- filename Name of the file parsed, only used to raise accurate error messages. infos Information returned by FFmpeg. fps_source Indicates what source data will be preferably used to retrieve fps data. check_duration Enable or disable the parsing of the duration of the file. Useful to skip the duration check, for example, for images. decode_file Indicates if the whole file must be read to retrieve their duration. This is needed for some files in order to get the correct duration (see https://github.com/Zulko/moviepy/pull/1222).
Get the information of a file using ffmpeg.
745
832
def ffmpeg_parse_infos( filename, check_duration=True, fps_source="fps", decode_file=False, print_infos=False, ): """Get the information of a file using ffmpeg. Returns a dictionary with next fields: - ``"duration"`` - ``"metadata"`` - ``"inputs"`` - ``"video_found"`` - ``"video_fps"`` - ``"video_n_frames"`` - ``"video_duration"`` - ``"video_bitrate"`` - ``"video_metadata"`` - ``"audio_found"`` - ``"audio_fps"`` - ``"audio_bitrate"`` - ``"audio_metadata"`` Note that "video_duration" is slightly smaller than "duration" to avoid fetching the incomplete frames at the end, which raises an error. Parameters ---------- filename Name of the file parsed, only used to raise accurate error messages. infos Information returned by FFmpeg. fps_source Indicates what source data will be preferably used to retrieve fps data. check_duration Enable or disable the parsing of the duration of the file. Useful to skip the duration check, for example, for images. decode_file Indicates if the whole file must be read to retrieve their duration. This is needed for some files in order to get the correct duration (see https://github.com/Zulko/moviepy/pull/1222). """ # Open the file in a pipe, read output cmd = [FFMPEG_BINARY, "-hide_banner", "-i", filename] if decode_file: cmd.extend(["-f", "null", "-"]) popen_params = cross_platform_popen_params( { "bufsize": 10**5, "stdout": sp.PIPE, "stderr": sp.PIPE, "stdin": sp.DEVNULL, } ) proc = sp.Popen(cmd, **popen_params) (output, error) = proc.communicate() infos = error.decode("utf8", errors="ignore") proc.terminate() del proc if print_infos: # print the whole info text returned by FFMPEG print(infos) try: return FFmpegInfosParser( infos, filename, fps_source=fps_source, check_duration=check_duration, decode_file=decode_file, ).parse() except Exception as exc: if os.path.isdir(filename): raise IsADirectoryError(f"'{filename}' is a directory") elif not os.path.exists(filename): raise FileNotFoundError(f"'{filename}' not found") raise IOError(f"Error passing `ffmpeg -i` command output:\n\n{infos}") from exc
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L745-L832
46
[ 0, 49, 50, 51, 52, 53, 54, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, 75 ]
22.727273
[ 72, 82, 83, 84, 85, 86, 87 ]
7.954545
false
89.814815
88
6
92.045455
41
def ffmpeg_parse_infos( filename, check_duration=True, fps_source="fps", decode_file=False, print_infos=False, ): # Open the file in a pipe, read output cmd = [FFMPEG_BINARY, "-hide_banner", "-i", filename] if decode_file: cmd.extend(["-f", "null", "-"]) popen_params = cross_platform_popen_params( { "bufsize": 10**5, "stdout": sp.PIPE, "stderr": sp.PIPE, "stdin": sp.DEVNULL, } ) proc = sp.Popen(cmd, **popen_params) (output, error) = proc.communicate() infos = error.decode("utf8", errors="ignore") proc.terminate() del proc if print_infos: # print the whole info text returned by FFMPEG print(infos) try: return FFmpegInfosParser( infos, filename, fps_source=fps_source, check_duration=check_duration, decode_file=decode_file, ).parse() except Exception as exc: if os.path.isdir(filename): raise IsADirectoryError(f"'{filename}' is a directory") elif not os.path.exists(filename): raise FileNotFoundError(f"'{filename}' not found") raise IOError(f"Error passing `ffmpeg -i` command output:\n\n{infos}") from exc
28,503
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.__init__
( self, filename, decode_file=True, print_infos=False, bufsize=None, pixel_format="rgb24", check_duration=True, target_resolution=None, resize_algo="bicubic", fps_source="fps", )
16
75
def __init__( self, filename, decode_file=True, print_infos=False, bufsize=None, pixel_format="rgb24", check_duration=True, target_resolution=None, resize_algo="bicubic", fps_source="fps", ): self.filename = filename self.proc = None infos = ffmpeg_parse_infos( filename, check_duration=check_duration, fps_source=fps_source, decode_file=decode_file, print_infos=print_infos, ) self.fps = infos["video_fps"] self.size = infos["video_size"] # ffmpeg automatically rotates videos if rotation information is # available, so exchange width and height self.rotation = abs(infos.get("video_rotation", 0)) if self.rotation in [90, 270]: self.size = [self.size[1], self.size[0]] if target_resolution: if None in target_resolution: ratio = 1 for idx, target in enumerate(target_resolution): if target: ratio = target / self.size[idx] self.size = (int(self.size[0] * ratio), int(self.size[1] * ratio)) else: self.size = target_resolution self.resize_algo = resize_algo self.duration = infos["video_duration"] self.ffmpeg_duration = infos["duration"] self.n_frames = infos["video_n_frames"] self.bitrate = infos["video_bitrate"] self.infos = infos self.pixel_format = pixel_format self.depth = 4 if pixel_format[-1] == "a" else 3 # 'a' represents 'alpha' which means that each pixel has 4 values instead of 3. # See https://github.com/Zulko/moviepy/issues/1070#issuecomment-644457274 if bufsize is None: w, h = self.size bufsize = self.depth * w * h + 100 self.bufsize = bufsize self.initialize()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L16-L75
46
[ 0, 12, 13, 14, 15, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59 ]
70
[]
0
false
89.814815
60
7
100
0
def __init__( self, filename, decode_file=True, print_infos=False, bufsize=None, pixel_format="rgb24", check_duration=True, target_resolution=None, resize_algo="bicubic", fps_source="fps", ): self.filename = filename self.proc = None infos = ffmpeg_parse_infos( filename, check_duration=check_duration, fps_source=fps_source, decode_file=decode_file, print_infos=print_infos, ) self.fps = infos["video_fps"] self.size = infos["video_size"] # ffmpeg automatically rotates videos if rotation information is # available, so exchange width and height self.rotation = abs(infos.get("video_rotation", 0)) if self.rotation in [90, 270]: self.size = [self.size[1], self.size[0]] if target_resolution: if None in target_resolution: ratio = 1 for idx, target in enumerate(target_resolution): if target: ratio = target / self.size[idx] self.size = (int(self.size[0] * ratio), int(self.size[1] * ratio)) else: self.size = target_resolution self.resize_algo = resize_algo self.duration = infos["video_duration"] self.ffmpeg_duration = infos["duration"] self.n_frames = infos["video_n_frames"] self.bitrate = infos["video_bitrate"] self.infos = infos self.pixel_format = pixel_format self.depth = 4 if pixel_format[-1] == "a" else 3 # 'a' represents 'alpha' which means that each pixel has 4 values instead of 3. # See https://github.com/Zulko/moviepy/issues/1070#issuecomment-644457274 if bufsize is None: w, h = self.size bufsize = self.depth * w * h + 100 self.bufsize = bufsize self.initialize()
28,504
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.initialize
(self, start_time=0)
Opens the file, creates the pipe. Sets self.pos to the appropriate value (1 if start_time == 0 because it pre-reads the first frame).
Opens the file, creates the pipe.
77
132
def initialize(self, start_time=0): """ Opens the file, creates the pipe. Sets self.pos to the appropriate value (1 if start_time == 0 because it pre-reads the first frame). """ self.close(delete_lastread=False) # if any if start_time != 0: offset = min(1, start_time) i_arg = [ "-ss", "%.06f" % (start_time - offset), "-i", self.filename, "-ss", "%.06f" % offset, ] else: i_arg = ["-i", self.filename] cmd = ( [FFMPEG_BINARY] + i_arg + [ "-loglevel", "error", "-f", "image2pipe", "-vf", "scale=%d:%d" % tuple(self.size), "-sws_flags", self.resize_algo, "-pix_fmt", self.pixel_format, "-vcodec", "rawvideo", "-", ] ) popen_params = cross_platform_popen_params( { "bufsize": self.bufsize, "stdout": sp.PIPE, "stderr": sp.PIPE, "stdin": sp.DEVNULL, } ) self.proc = sp.Popen(cmd, **popen_params) # self.pos represents the (0-indexed) index of the frame that is next in line # to be read by self.read_frame(). # Eg when self.pos is 1, the 2nd frame will be read next. self.pos = self.get_frame_number(start_time) self.lastread = self.read_frame()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L77-L132
46
[ 0, 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 ]
100
[]
0
true
89.814815
56
2
100
4
def initialize(self, start_time=0): self.close(delete_lastread=False) # if any if start_time != 0: offset = min(1, start_time) i_arg = [ "-ss", "%.06f" % (start_time - offset), "-i", self.filename, "-ss", "%.06f" % offset, ] else: i_arg = ["-i", self.filename] cmd = ( [FFMPEG_BINARY] + i_arg + [ "-loglevel", "error", "-f", "image2pipe", "-vf", "scale=%d:%d" % tuple(self.size), "-sws_flags", self.resize_algo, "-pix_fmt", self.pixel_format, "-vcodec", "rawvideo", "-", ] ) popen_params = cross_platform_popen_params( { "bufsize": self.bufsize, "stdout": sp.PIPE, "stderr": sp.PIPE, "stdin": sp.DEVNULL, } ) self.proc = sp.Popen(cmd, **popen_params) # self.pos represents the (0-indexed) index of the frame that is next in line # to be read by self.read_frame(). # Eg when self.pos is 1, the 2nd frame will be read next. self.pos = self.get_frame_number(start_time) self.lastread = self.read_frame()
28,505
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.skip_frames
(self, n=1)
Reads and throws away n frames
Reads and throws away n frames
134
141
def skip_frames(self, n=1): """Reads and throws away n frames""" w, h = self.size for i in range(n): self.proc.stdout.read(self.depth * w * h) # self.proc.stdout.flush() self.pos += n
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L134-L141
46
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
89.814815
8
2
100
1
def skip_frames(self, n=1): w, h = self.size for i in range(n): self.proc.stdout.read(self.depth * w * h) # self.proc.stdout.flush() self.pos += n
28,506
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.read_frame
(self)
return result
Reads the next frame from the file. Note that upon (re)initialization, the first frame will already have been read and stored in ``self.lastread``.
Reads the next frame from the file. Note that upon (re)initialization, the first frame will already have been read and stored in ``self.lastread``.
143
197
def read_frame(self): """ Reads the next frame from the file. Note that upon (re)initialization, the first frame will already have been read and stored in ``self.lastread``. """ w, h = self.size nbytes = self.depth * w * h s = self.proc.stdout.read(nbytes) if len(s) != nbytes: warnings.warn( ( "In file %s, %d bytes wanted but %d bytes read at frame index" " %d (out of a total %d frames), at time %.02f/%.02f sec." " Using the last valid frame instead." ) % ( self.filename, nbytes, len(s), self.pos, self.n_frames, 1.0 * self.pos / self.fps, self.duration, ), UserWarning, ) if not hasattr(self, "last_read"): raise IOError( ( "MoviePy error: failed to read the first frame of " f"video file {self.filename}. That might mean that the file is " "corrupted. That may also mean that you are using " "a deprecated version of FFMPEG. On Ubuntu/Debian " "for instance the version in the repos is deprecated. " "Please update to a recent version from the website." ) ) result = self.last_read else: if hasattr(np, "frombuffer"): result = np.frombuffer(s, dtype="uint8") else: result = np.fromstring(s, dtype="uint8") result.shape = (h, w, len(s) // (w * h)) # reshape((h, w, len(s)//(w*h))) self.last_read = result # We have to do this down here because `self.pos` is used in the warning above self.pos += 1 return result
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L143-L197
46
[ 0, 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, 40, 41, 42, 43, 44, 45, 46, 48, 49, 50, 51, 52, 53, 54 ]
80
[ 30, 47 ]
3.636364
false
89.814815
55
4
96.363636
3
def read_frame(self): w, h = self.size nbytes = self.depth * w * h s = self.proc.stdout.read(nbytes) if len(s) != nbytes: warnings.warn( ( "In file %s, %d bytes wanted but %d bytes read at frame index" " %d (out of a total %d frames), at time %.02f/%.02f sec." " Using the last valid frame instead." ) % ( self.filename, nbytes, len(s), self.pos, self.n_frames, 1.0 * self.pos / self.fps, self.duration, ), UserWarning, ) if not hasattr(self, "last_read"): raise IOError( ( "MoviePy error: failed to read the first frame of " f"video file {self.filename}. That might mean that the file is " "corrupted. That may also mean that you are using " "a deprecated version of FFMPEG. On Ubuntu/Debian " "for instance the version in the repos is deprecated. " "Please update to a recent version from the website." ) ) result = self.last_read else: if hasattr(np, "frombuffer"): result = np.frombuffer(s, dtype="uint8") else: result = np.fromstring(s, dtype="uint8") result.shape = (h, w, len(s) // (w * h)) # reshape((h, w, len(s)//(w*h))) self.last_read = result # We have to do this down here because `self.pos` is used in the warning above self.pos += 1 return result
28,507
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.get_frame
(self, t)
Read a file video frame at time t. Note for coders: getting an arbitrary frame in the video with ffmpeg can be painfully slow if some decoding has to be done. This function tries to avoid fetching arbitrary frames whenever possible, by moving between adjacent frames.
Read a file video frame at time t.
199
227
def get_frame(self, t): """Read a file video frame at time t. Note for coders: getting an arbitrary frame in the video with ffmpeg can be painfully slow if some decoding has to be done. This function tries to avoid fetching arbitrary frames whenever possible, by moving between adjacent frames. """ # + 1 so that it represents the frame position that it will be # after the frame is read. This makes the later comparisons easier. pos = self.get_frame_number(t) + 1 # Initialize proc if it is not open if not self.proc: print("Proc not detected") self.initialize(t) return self.last_read if pos == self.pos: return self.last_read elif (pos < self.pos) or (pos > self.pos + 100): # We can't just skip forward to `pos` or it would take too long self.initialize(t) return self.lastread else: # If pos == self.pos + 1, this line has no effect self.skip_frames(pos - self.pos - 1) result = self.read_frame() return result
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L199-L227
46
[ 0, 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 ]
100
[]
0
true
89.814815
29
5
100
6
def get_frame(self, t): # + 1 so that it represents the frame position that it will be # after the frame is read. This makes the later comparisons easier. pos = self.get_frame_number(t) + 1 # Initialize proc if it is not open if not self.proc: print("Proc not detected") self.initialize(t) return self.last_read if pos == self.pos: return self.last_read elif (pos < self.pos) or (pos > self.pos + 100): # We can't just skip forward to `pos` or it would take too long self.initialize(t) return self.lastread else: # If pos == self.pos + 1, this line has no effect self.skip_frames(pos - self.pos - 1) result = self.read_frame() return result
28,508
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.get_frame_number
(self, t)
return int(self.fps * t + 0.00001)
Helper method to return the frame number at time ``t``
Helper method to return the frame number at time ``t``
229
235
def get_frame_number(self, t): """Helper method to return the frame number at time ``t``""" # I used this horrible '+0.00001' hack because sometimes due to numerical # imprecisions a 3.0 can become a 2.99999999... which makes the int() # go to the previous integer. This makes the fetching more robust when you # are getting the nth frame by writing get_frame(n/fps). return int(self.fps * t + 0.00001)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L229-L235
46
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
89.814815
7
1
100
1
def get_frame_number(self, t): # I used this horrible '+0.00001' hack because sometimes due to numerical # imprecisions a 3.0 can become a 2.99999999... which makes the int() # go to the previous integer. This makes the fetching more robust when you # are getting the nth frame by writing get_frame(n/fps). return int(self.fps * t + 0.00001)
28,509
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.close
(self, delete_lastread=True)
Closes the reader terminating the process, if is still open.
Closes the reader terminating the process, if is still open.
237
247
def close(self, delete_lastread=True): """Closes the reader terminating the process, if is still open.""" if self.proc: if self.proc.poll() is None: self.proc.terminate() self.proc.stdout.close() self.proc.stderr.close() self.proc.wait() self.proc = None if delete_lastread and hasattr(self, "last_read"): del self.last_read
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L237-L247
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
89.814815
11
5
100
1
def close(self, delete_lastread=True): if self.proc: if self.proc.poll() is None: self.proc.terminate() self.proc.stdout.close() self.proc.stderr.close() self.proc.wait() self.proc = None if delete_lastread and hasattr(self, "last_read"): del self.last_read
28,510
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFMPEG_VideoReader.__del__
(self)
249
250
def __del__(self): self.close()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L249-L250
46
[ 0, 1 ]
100
[]
0
true
89.814815
2
1
100
0
def __del__(self): self.close()
28,511
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.__init__
( self, infos, filename, fps_source="fps", check_duration=True, decode_file=False, )
315
329
def __init__( self, infos, filename, fps_source="fps", check_duration=True, decode_file=False, ): self.infos = infos self.filename = filename self.check_duration = check_duration self.fps_source = fps_source self.duration_tag_separator = "time=" if decode_file else "Duration: " self._reset_state()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L315-L329
46
[ 0, 8, 9, 10, 11, 12, 13, 14 ]
53.333333
[]
0
false
89.814815
15
1
100
0
def __init__( self, infos, filename, fps_source="fps", check_duration=True, decode_file=False, ): self.infos = infos self.filename = filename self.check_duration = check_duration self.fps_source = fps_source self.duration_tag_separator = "time=" if decode_file else "Duration: " self._reset_state()
28,512
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser._reset_state
(self)
Reinitializes the state of the parser. Used internally at initialization and at the end of the parsing process.
Reinitializes the state of the parser. Used internally at initialization and at the end of the parsing process.
331
365
def _reset_state(self): """Reinitializes the state of the parser. Used internally at initialization and at the end of the parsing process. """ # could be 2 possible types of metadata: # - file_metadata: Metadata of the container. Here are the tags set # by the user using `-metadata` ffmpeg option # - stream_metadata: Metadata for each stream of the container. self._inside_file_metadata = False # this state is needed if `duration_tag_separator == "time="` because # execution of ffmpeg decoding the whole file using `-f null -` appends # to the output the blocks "Stream mapping:" and "Output:", which # should be ignored self._inside_output = False # flag which indicates that a default stream has not been found yet self._default_stream_found = False # current input file, stream and chapter, which will be built at runtime self._current_input_file = {"streams": []} self._current_stream = None self._current_chapter = None # resulting data of the parsing process self.result = { "video_found": False, "audio_found": False, "metadata": {}, "inputs": [], } # keep the value of latest metadata value parsed so we can build # at next lines a multiline metadata value self._last_metadata_field_added = None
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L331-L365
46
[ 0, 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 ]
100
[]
0
true
89.814815
35
1
100
2
def _reset_state(self): # could be 2 possible types of metadata: # - file_metadata: Metadata of the container. Here are the tags set # by the user using `-metadata` ffmpeg option # - stream_metadata: Metadata for each stream of the container. self._inside_file_metadata = False # this state is needed if `duration_tag_separator == "time="` because # execution of ffmpeg decoding the whole file using `-f null -` appends # to the output the blocks "Stream mapping:" and "Output:", which # should be ignored self._inside_output = False # flag which indicates that a default stream has not been found yet self._default_stream_found = False # current input file, stream and chapter, which will be built at runtime self._current_input_file = {"streams": []} self._current_stream = None self._current_chapter = None # resulting data of the parsing process self.result = { "video_found": False, "audio_found": False, "metadata": {}, "inputs": [], } # keep the value of latest metadata value parsed so we can build # at next lines a multiline metadata value self._last_metadata_field_added = None
28,513
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse
(self)
return result
Parses the information returned by FFmpeg in stderr executing their binary for a file with ``-i`` option and returns a dictionary with all data needed by MoviePy.
Parses the information returned by FFmpeg in stderr executing their binary for a file with ``-i`` option and returns a dictionary with all data needed by MoviePy.
367
596
def parse(self): """Parses the information returned by FFmpeg in stderr executing their binary for a file with ``-i`` option and returns a dictionary with all data needed by MoviePy. """ # chapters by input file input_chapters = [] for line in self.infos.splitlines()[1:]: if ( self.duration_tag_separator == "time=" and self.check_duration and "time=" in line ): # parse duration using file decodification self.result["duration"] = self.parse_duration(line) elif self._inside_output or line[0] != " ": if self.duration_tag_separator == "time=" and not self._inside_output: self._inside_output = True # skip lines like "At least one output file must be specified" elif not self._inside_file_metadata and line.startswith(" Metadata:"): # enter " Metadata:" group self._inside_file_metadata = True elif line.startswith(" Duration:"): # exit " Metadata:" group self._inside_file_metadata = False if self.check_duration and self.duration_tag_separator == "Duration: ": self.result["duration"] = self.parse_duration(line) # parse global bitrate (in kb/s) bitrate_match = re.search(r"bitrate: (\d+) kb/s", line) self.result["bitrate"] = ( int(bitrate_match.group(1)) if bitrate_match else None ) # parse start time (in seconds) start_match = re.search(r"start: (\d+\.?\d+)", line) self.result["start"] = ( float(start_match.group(1)) if start_match else None ) elif self._inside_file_metadata: # file metadata line field, value = self.parse_metadata_field_value(line) # multiline metadata value parsing if field == "": field = self._last_metadata_field_added value = self.result["metadata"][field] + "\n" + value else: self._last_metadata_field_added = field self.result["metadata"][field] = value elif line.lstrip().startswith("Stream "): # exit stream " Metadata:" if self._current_stream: self._current_input_file["streams"].append(self._current_stream) # get input number, stream number, language and type main_info_match = re.search( r"^Stream\s#(\d+):(\d+)(?:\[\w+\])?\(?(\w+)?\)?:\s(\w+):", line.lstrip(), ) ( input_number, stream_number, language, stream_type, ) = main_info_match.groups() input_number = int(input_number) stream_number = int(stream_number) stream_type_lower = stream_type.lower() if language == "und": language = None # start builiding the current stream self._current_stream = { "input_number": input_number, "stream_number": stream_number, "stream_type": stream_type_lower, "language": language, "default": not self._default_stream_found or line.endswith("(default)"), } self._default_stream_found = True # for default streams, set their numbers globally, so it's # easy to get without iterating all if self._current_stream["default"]: self.result[ f"default_{stream_type_lower}_input_number" ] = input_number self.result[ f"default_{stream_type_lower}_stream_number" ] = stream_number # exit chapter if self._current_chapter: input_chapters[input_number].append(self._current_chapter) self._current_chapter = None if "input_number" not in self._current_input_file: # first input file self._current_input_file["input_number"] = input_number elif self._current_input_file["input_number"] != input_number: # new input file # include their chapters if there are for this input file if len(input_chapters) >= input_number + 1: self._current_input_file["chapters"] = input_chapters[ input_number ] # add new input file to self.result self.result["inputs"].append(self._current_input_file) self._current_input_file = {"input_number": input_number} # parse relevant data by stream type try: global_data, stream_data = self.parse_data_by_stream_type( stream_type, line ) except NotImplementedError as exc: warnings.warn( f"{str(exc)}\nffmpeg output:\n\n{self.infos}", UserWarning ) else: self.result.update(global_data) self._current_stream.update(stream_data) elif line.startswith(" Metadata:"): # enter group " Metadata:" continue elif self._current_stream: # stream metadata line if "metadata" not in self._current_stream: self._current_stream["metadata"] = {} field, value = self.parse_metadata_field_value(line) if self._current_stream["stream_type"] == "video": field, value = self.video_metadata_type_casting(field, value) if field == "rotate": self.result["video_rotation"] = value # multiline metadata value parsing if field == "": field = self._last_metadata_field_added value = self._current_stream["metadata"][field] + "\n" + value else: self._last_metadata_field_added = field self._current_stream["metadata"][field] = value elif line.startswith(" Chapter"): # Chapter data line if self._current_chapter: # there is a previews chapter? if len(input_chapters) < self._current_chapter["input_number"] + 1: input_chapters.append([]) # include in the chapters by input matrix input_chapters[self._current_chapter["input_number"]].append( self._current_chapter ) # extract chapter data chapter_data_match = re.search( r"^ Chapter #(\d+):(\d+): start (\d+\.?\d+?), end (\d+\.?\d+?)", line, ) input_number, chapter_number, start, end = chapter_data_match.groups() # start building the chapter self._current_chapter = { "input_number": int(input_number), "chapter_number": int(chapter_number), "start": float(start), "end": float(end), } elif self._current_chapter: # inside chapter metadata if "metadata" not in self._current_chapter: self._current_chapter["metadata"] = {} field, value = self.parse_metadata_field_value(line) # multiline metadata value parsing if field == "": field = self._last_metadata_field_added value = self._current_chapter["metadata"][field] + "\n" + value else: self._last_metadata_field_added = field self._current_chapter["metadata"][field] = value # last input file, must be included in self.result if self._current_input_file: self._current_input_file["streams"].append(self._current_stream) # include their chapters, if there are if len(input_chapters) == self._current_input_file["input_number"] + 1: self._current_input_file["chapters"] = input_chapters[ self._current_input_file["input_number"] ] self.result["inputs"].append(self._current_input_file) # some video duration utilities if self.result["video_found"] and self.check_duration: self.result["video_n_frames"] = int( self.result["duration"] * self.result["video_fps"] ) self.result["video_duration"] = self.result["duration"] else: self.result["video_n_frames"] = 1 self.result["video_duration"] = None # We could have also recomputed duration from the number of frames, as follows: # >>> result['video_duration'] = result['video_n_frames'] / result['video_fps'] # not default audio found, assume first audio stream is the default if self.result["audio_found"] and not self.result.get("audio_bitrate"): self.result["audio_bitrate"] = None for streams_input in self.result["inputs"]: for stream in streams_input["streams"]: if stream["stream_type"] == "audio" and stream.get("bitrate"): self.result["audio_bitrate"] = stream["bitrate"] break if self.result["audio_bitrate"] is not None: break result = self.result # reset state of the parser self._reset_state() return result
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L367-L596
46
[ 0, 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, 116, 117, 118, 119, 120, 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, 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 ]
93.478261
[ 107, 108, 113, 114, 121, 122, 183, 184 ]
3.478261
false
89.814815
230
49
96.521739
3
def parse(self): # chapters by input file input_chapters = [] for line in self.infos.splitlines()[1:]: if ( self.duration_tag_separator == "time=" and self.check_duration and "time=" in line ): # parse duration using file decodification self.result["duration"] = self.parse_duration(line) elif self._inside_output or line[0] != " ": if self.duration_tag_separator == "time=" and not self._inside_output: self._inside_output = True # skip lines like "At least one output file must be specified" elif not self._inside_file_metadata and line.startswith(" Metadata:"): # enter " Metadata:" group self._inside_file_metadata = True elif line.startswith(" Duration:"): # exit " Metadata:" group self._inside_file_metadata = False if self.check_duration and self.duration_tag_separator == "Duration: ": self.result["duration"] = self.parse_duration(line) # parse global bitrate (in kb/s) bitrate_match = re.search(r"bitrate: (\d+) kb/s", line) self.result["bitrate"] = ( int(bitrate_match.group(1)) if bitrate_match else None ) # parse start time (in seconds) start_match = re.search(r"start: (\d+\.?\d+)", line) self.result["start"] = ( float(start_match.group(1)) if start_match else None ) elif self._inside_file_metadata: # file metadata line field, value = self.parse_metadata_field_value(line) # multiline metadata value parsing if field == "": field = self._last_metadata_field_added value = self.result["metadata"][field] + "\n" + value else: self._last_metadata_field_added = field self.result["metadata"][field] = value elif line.lstrip().startswith("Stream "): # exit stream " Metadata:" if self._current_stream: self._current_input_file["streams"].append(self._current_stream) # get input number, stream number, language and type main_info_match = re.search( r"^Stream\s#(\d+):(\d+)(?:\[\w+\])?\(?(\w+)?\)?:\s(\w+):", line.lstrip(), ) ( input_number, stream_number, language, stream_type, ) = main_info_match.groups() input_number = int(input_number) stream_number = int(stream_number) stream_type_lower = stream_type.lower() if language == "und": language = None # start builiding the current stream self._current_stream = { "input_number": input_number, "stream_number": stream_number, "stream_type": stream_type_lower, "language": language, "default": not self._default_stream_found or line.endswith("(default)"), } self._default_stream_found = True # for default streams, set their numbers globally, so it's # easy to get without iterating all if self._current_stream["default"]: self.result[ f"default_{stream_type_lower}_input_number" ] = input_number self.result[ f"default_{stream_type_lower}_stream_number" ] = stream_number # exit chapter if self._current_chapter: input_chapters[input_number].append(self._current_chapter) self._current_chapter = None if "input_number" not in self._current_input_file: # first input file self._current_input_file["input_number"] = input_number elif self._current_input_file["input_number"] != input_number: # new input file # include their chapters if there are for this input file if len(input_chapters) >= input_number + 1: self._current_input_file["chapters"] = input_chapters[ input_number ] # add new input file to self.result self.result["inputs"].append(self._current_input_file) self._current_input_file = {"input_number": input_number} # parse relevant data by stream type try: global_data, stream_data = self.parse_data_by_stream_type( stream_type, line ) except NotImplementedError as exc: warnings.warn( f"{str(exc)}\nffmpeg output:\n\n{self.infos}", UserWarning ) else: self.result.update(global_data) self._current_stream.update(stream_data) elif line.startswith(" Metadata:"): # enter group " Metadata:" continue elif self._current_stream: # stream metadata line if "metadata" not in self._current_stream: self._current_stream["metadata"] = {} field, value = self.parse_metadata_field_value(line) if self._current_stream["stream_type"] == "video": field, value = self.video_metadata_type_casting(field, value) if field == "rotate": self.result["video_rotation"] = value # multiline metadata value parsing if field == "": field = self._last_metadata_field_added value = self._current_stream["metadata"][field] + "\n" + value else: self._last_metadata_field_added = field self._current_stream["metadata"][field] = value elif line.startswith(" Chapter"): # Chapter data line if self._current_chapter: # there is a previews chapter? if len(input_chapters) < self._current_chapter["input_number"] + 1: input_chapters.append([]) # include in the chapters by input matrix input_chapters[self._current_chapter["input_number"]].append( self._current_chapter ) # extract chapter data chapter_data_match = re.search( r"^ Chapter #(\d+):(\d+): start (\d+\.?\d+?), end (\d+\.?\d+?)", line, ) input_number, chapter_number, start, end = chapter_data_match.groups() # start building the chapter self._current_chapter = { "input_number": int(input_number), "chapter_number": int(chapter_number), "start": float(start), "end": float(end), } elif self._current_chapter: # inside chapter metadata if "metadata" not in self._current_chapter: self._current_chapter["metadata"] = {} field, value = self.parse_metadata_field_value(line) # multiline metadata value parsing if field == "": field = self._last_metadata_field_added value = self._current_chapter["metadata"][field] + "\n" + value else: self._last_metadata_field_added = field self._current_chapter["metadata"][field] = value # last input file, must be included in self.result if self._current_input_file: self._current_input_file["streams"].append(self._current_stream) # include their chapters, if there are if len(input_chapters) == self._current_input_file["input_number"] + 1: self._current_input_file["chapters"] = input_chapters[ self._current_input_file["input_number"] ] self.result["inputs"].append(self._current_input_file) # some video duration utilities if self.result["video_found"] and self.check_duration: self.result["video_n_frames"] = int( self.result["duration"] * self.result["video_fps"] ) self.result["video_duration"] = self.result["duration"] else: self.result["video_n_frames"] = 1 self.result["video_duration"] = None # We could have also recomputed duration from the number of frames, as follows: # >>> result['video_duration'] = result['video_n_frames'] / result['video_fps'] # not default audio found, assume first audio stream is the default if self.result["audio_found"] and not self.result.get("audio_bitrate"): self.result["audio_bitrate"] = None for streams_input in self.result["inputs"]: for stream in streams_input["streams"]: if stream["stream_type"] == "audio" and stream.get("bitrate"): self.result["audio_bitrate"] = stream["bitrate"] break if self.result["audio_bitrate"] is not None: break result = self.result # reset state of the parser self._reset_state() return result
28,514
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_data_by_stream_type
(self, stream_type, line)
Parses data from "Stream ... {stream_type}" line.
Parses data from "Stream ... {stream_type}" line.
598
610
def parse_data_by_stream_type(self, stream_type, line): """Parses data from "Stream ... {stream_type}" line.""" try: return { "Audio": self.parse_audio_stream_data, "Video": self.parse_video_stream_data, "Data": lambda _line: ({}, {}), }[stream_type](line) except KeyError: raise NotImplementedError( f"{stream_type} stream parsing is not supported by moviepy and" " will be ignored" )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L598-L610
46
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
61.538462
[ 8, 9 ]
15.384615
false
89.814815
13
2
84.615385
1
def parse_data_by_stream_type(self, stream_type, line): try: return { "Audio": self.parse_audio_stream_data, "Video": self.parse_video_stream_data, "Data": lambda _line: ({}, {}), }[stream_type](line) except KeyError: raise NotImplementedError( f"{stream_type} stream parsing is not supported by moviepy and" " will be ignored" )
28,515
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_audio_stream_data
(self, line)
return (global_data, stream_data)
Parses data from "Stream ... Audio" line.
Parses data from "Stream ... Audio" line.
612
628
def parse_audio_stream_data(self, line): """Parses data from "Stream ... Audio" line.""" global_data, stream_data = ({"audio_found": True}, {}) try: stream_data["fps"] = int(re.search(r" (\d+) Hz", line).group(1)) except (AttributeError, ValueError): # AttributeError: 'NoneType' object has no attribute 'group' # ValueError: invalid literal for int() with base 10: '<string>' stream_data["fps"] = "unknown" match_audio_bitrate = re.search(r"(\d+) kb/s", line) stream_data["bitrate"] = ( int(match_audio_bitrate.group(1)) if match_audio_bitrate else None ) if self._current_stream["default"]: global_data["audio_fps"] = stream_data["fps"] global_data["audio_bitrate"] = stream_data["bitrate"] return (global_data, stream_data)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L612-L628
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
89.814815
17
3
100
1
def parse_audio_stream_data(self, line): global_data, stream_data = ({"audio_found": True}, {}) try: stream_data["fps"] = int(re.search(r" (\d+) Hz", line).group(1)) except (AttributeError, ValueError): # AttributeError: 'NoneType' object has no attribute 'group' # ValueError: invalid literal for int() with base 10: '<string>' stream_data["fps"] = "unknown" match_audio_bitrate = re.search(r"(\d+) kb/s", line) stream_data["bitrate"] = ( int(match_audio_bitrate.group(1)) if match_audio_bitrate else None ) if self._current_stream["default"]: global_data["audio_fps"] = stream_data["fps"] global_data["audio_bitrate"] = stream_data["bitrate"] return (global_data, stream_data)
28,516
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_video_stream_data
(self, line)
return (global_data, stream_data)
Parses data from "Stream ... Video" line.
Parses data from "Stream ... Video" line.
630
691
def parse_video_stream_data(self, line): """Parses data from "Stream ... Video" line.""" global_data, stream_data = ({"video_found": True}, {}) try: match_video_size = re.search(r" (\d+)x(\d+)[,\s]", line) if match_video_size: # size, of the form 460x320 (w x h) stream_data["size"] = [int(num) for num in match_video_size.groups()] except Exception: raise IOError( ( "MoviePy error: failed to read video dimensions in" " file '%s'.\nHere are the file infos returned by" "ffmpeg:\n\n%s" ) % (self.filename, self.infos) ) match_bitrate = re.search(r"(\d+) kb/s", line) stream_data["bitrate"] = int(match_bitrate.group(1)) if match_bitrate else None # Get the frame rate. Sometimes it's 'tbr', sometimes 'fps', sometimes # tbc, and sometimes tbc/2... # Current policy: Trust fps first, then tbr unless fps_source is # specified as 'tbr' in which case try tbr then fps # If result is near from x*1000/1001 where x is 23,24,25,50, # replace by x*1000/1001 (very common case for the fps). if self.fps_source == "fps": try: fps = self.parse_fps(line) except (AttributeError, ValueError): fps = self.parse_tbr(line) elif self.fps_source == "tbr": try: fps = self.parse_tbr(line) except (AttributeError, ValueError): fps = self.parse_fps(line) else: raise ValueError( ("fps source '%s' not supported parsing the video '%s'") % (self.fps_source, self.filename) ) # It is known that a fps of 24 is often written as 24000/1001 # but then ffmpeg nicely rounds it to 23.98, which we hate. coef = 1000.0 / 1001.0 for x in [23, 24, 25, 30, 50]: if (fps != x) and abs(fps - x * coef) < 0.01: fps = x * coef stream_data["fps"] = fps if self._current_stream["default"] or "video_size" not in self.result: global_data["video_size"] = stream_data.get("size", None) if self._current_stream["default"] or "video_bitrate" not in self.result: global_data["video_bitrate"] = stream_data.get("bitrate", None) if self._current_stream["default"] or "video_fps" not in self.result: global_data["video_fps"] = stream_data["fps"] return (global_data, stream_data)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L630-L691
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 47, 48, 49, 50, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61 ]
69.354839
[ 9, 10, 38, 39, 41, 51 ]
9.677419
false
89.814815
62
17
90.322581
1
def parse_video_stream_data(self, line): global_data, stream_data = ({"video_found": True}, {}) try: match_video_size = re.search(r" (\d+)x(\d+)[,\s]", line) if match_video_size: # size, of the form 460x320 (w x h) stream_data["size"] = [int(num) for num in match_video_size.groups()] except Exception: raise IOError( ( "MoviePy error: failed to read video dimensions in" " file '%s'.\nHere are the file infos returned by" "ffmpeg:\n\n%s" ) % (self.filename, self.infos) ) match_bitrate = re.search(r"(\d+) kb/s", line) stream_data["bitrate"] = int(match_bitrate.group(1)) if match_bitrate else None # Get the frame rate. Sometimes it's 'tbr', sometimes 'fps', sometimes # tbc, and sometimes tbc/2... # Current policy: Trust fps first, then tbr unless fps_source is # specified as 'tbr' in which case try tbr then fps # If result is near from x*1000/1001 where x is 23,24,25,50, # replace by x*1000/1001 (very common case for the fps). if self.fps_source == "fps": try: fps = self.parse_fps(line) except (AttributeError, ValueError): fps = self.parse_tbr(line) elif self.fps_source == "tbr": try: fps = self.parse_tbr(line) except (AttributeError, ValueError): fps = self.parse_fps(line) else: raise ValueError( ("fps source '%s' not supported parsing the video '%s'") % (self.fps_source, self.filename) ) # It is known that a fps of 24 is often written as 24000/1001 # but then ffmpeg nicely rounds it to 23.98, which we hate. coef = 1000.0 / 1001.0 for x in [23, 24, 25, 30, 50]: if (fps != x) and abs(fps - x * coef) < 0.01: fps = x * coef stream_data["fps"] = fps if self._current_stream["default"] or "video_size" not in self.result: global_data["video_size"] = stream_data.get("size", None) if self._current_stream["default"] or "video_bitrate" not in self.result: global_data["video_bitrate"] = stream_data.get("bitrate", None) if self._current_stream["default"] or "video_fps" not in self.result: global_data["video_fps"] = stream_data["fps"] return (global_data, stream_data)
28,517
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_fps
(self, line)
return float(re.search(r" (\d+.?\d*) fps", line).group(1))
Parses number of FPS from a line of the ``ffmpeg -i`` command output.
Parses number of FPS from a line of the ``ffmpeg -i`` command output.
693
695
def parse_fps(self, line): """Parses number of FPS from a line of the ``ffmpeg -i`` command output.""" return float(re.search(r" (\d+.?\d*) fps", line).group(1))
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L693-L695
46
[ 0, 1, 2 ]
100
[]
0
true
89.814815
3
1
100
1
def parse_fps(self, line): return float(re.search(r" (\d+.?\d*) fps", line).group(1))
28,518
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_tbr
(self, line)
return tbr
Parses number of TBS from a line of the ``ffmpeg -i`` command output.
Parses number of TBS from a line of the ``ffmpeg -i`` command output.
697
706
def parse_tbr(self, line): """Parses number of TBS from a line of the ``ffmpeg -i`` command output.""" s_tbr = re.search(r" (\d+.?\d*k?) tbr", line).group(1) # Sometimes comes as e.g. 12k. We need to replace that with 12000. if s_tbr[-1] == "k": tbr = float(s_tbr[:-1]) * 1000 else: tbr = float(s_tbr) return tbr
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L697-L706
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
100
[]
0
true
89.814815
10
2
100
1
def parse_tbr(self, line): s_tbr = re.search(r" (\d+.?\d*k?) tbr", line).group(1) # Sometimes comes as e.g. 12k. We need to replace that with 12000. if s_tbr[-1] == "k": tbr = float(s_tbr[:-1]) * 1000 else: tbr = float(s_tbr) return tbr
28,519
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_duration
(self, line)
Parse the duration from the line that outputs the duration of the container.
Parse the duration from the line that outputs the duration of the container.
708
726
def parse_duration(self, line): """Parse the duration from the line that outputs the duration of the container. """ try: time_raw_string = line.split(self.duration_tag_separator)[-1] match_duration = re.search( r"([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", time_raw_string, ) return convert_to_seconds(match_duration.group(1)) except Exception: raise IOError( ( "MoviePy error: failed to read the duration of file '%s'.\n" "Here are the file infos returned by ffmpeg:\n\n%s" ) % (self.filename, self.infos) )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L708-L726
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
57.894737
[ 11, 12 ]
10.526316
false
89.814815
19
2
89.473684
2
def parse_duration(self, line): try: time_raw_string = line.split(self.duration_tag_separator)[-1] match_duration = re.search( r"([0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9])", time_raw_string, ) return convert_to_seconds(match_duration.group(1)) except Exception: raise IOError( ( "MoviePy error: failed to read the duration of file '%s'.\n" "Here are the file infos returned by ffmpeg:\n\n%s" ) % (self.filename, self.infos) )
28,520
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.parse_metadata_field_value
( self, line, )
return (raw_field.strip(" "), raw_value.strip(" "))
Returns a tuple with a metadata field-value pair given a ffmpeg `-i` command output line.
Returns a tuple with a metadata field-value pair given a ffmpeg `-i` command output line.
728
736
def parse_metadata_field_value( self, line, ): """Returns a tuple with a metadata field-value pair given a ffmpeg `-i` command output line. """ raw_field, raw_value = line.split(":", 1) return (raw_field.strip(" "), raw_value.strip(" "))
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L728-L736
46
[ 0, 6, 7, 8 ]
44.444444
[]
0
false
89.814815
9
1
100
2
def parse_metadata_field_value( self, line, ): raw_field, raw_value = line.split(":", 1) return (raw_field.strip(" "), raw_value.strip(" "))
28,521
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_reader.py
FFmpegInfosParser.video_metadata_type_casting
(self, field, value)
return (field, value)
Cast needed video metadata fields to other types than the default str.
Cast needed video metadata fields to other types than the default str.
738
742
def video_metadata_type_casting(self, field, value): """Cast needed video metadata fields to other types than the default str.""" if field == "rotate": return (field, float(value)) return (field, value)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_reader.py#L738-L742
46
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
89.814815
5
2
100
1
def video_metadata_type_casting(self, field, value): if field == "rotate": return (field, float(value)) return (field, value)
28,522
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/sliders.py
sliders
(func, sliders_properties, wait_for_validation=False)
A light GUI to manually explore and tune the outputs of a function. ``slider_properties`` is a list of dicts (arguments for Slider):: def volume(x,y,z): return x*y*z intervals = [ { 'label' : 'width', 'valmin': 1 , 'valmax': 5 }, { 'label' : 'height', 'valmin': 1 , 'valmax': 5 }, { 'label' : 'depth', 'valmin': 1 , 'valmax': 5 } ] inputExplorer(volume, intervals)
A light GUI to manually explore and tune the outputs of a function.
7
72
def sliders(func, sliders_properties, wait_for_validation=False): """A light GUI to manually explore and tune the outputs of a function. ``slider_properties`` is a list of dicts (arguments for Slider):: def volume(x,y,z): return x*y*z intervals = [ { 'label' : 'width', 'valmin': 1 , 'valmax': 5 }, { 'label' : 'height', 'valmin': 1 , 'valmax': 5 }, { 'label' : 'depth', 'valmin': 1 , 'valmax': 5 } ] inputExplorer(volume, intervals) """ n_vars = len(sliders_properties) slider_width = 1.0 / n_vars # CREATE THE CANVAS figure, ax = plt.subplots(1) figure.canvas.set_window_title("Inputs for '%s'" % (func.func_name)) # choose an appropriate height width, height = figure.get_size_inches() height = min(0.5 * n_vars, 8) figure.set_size_inches(width, height, forward=True) # hide the axis ax.set_frame_on(False) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # CREATE THE SLIDERS sliders = [] for i, properties in enumerate(sliders_properties): ax = plt.axes( [0.1, 0.95 - 0.9 * (i + 1) * slider_width, 0.8, 0.8 * slider_width] ) if not isinstance(properties, dict): properties = dict(zip(["label", "valmin", "valmax", "valinit"], properties)) sliders.append(Slider(ax=ax, **properties)) # CREATE THE CALLBACK FUNCTIONS def on_changed(event): res = func(*(s.val for s in sliders)) if res is not None: print(res) def on_key_press(event): if event.key == "enter": on_changed(event) figure.canvas.mpl_connect("key_press_event", on_key_press) # AUTOMATIC UPDATE ? if not wait_for_validation: for s in sliders: s.on_changed(on_changed) # DISPLAY THE SLIDERS plt.show()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/sliders.py#L7-L72
46
[]
0
[ 0, 14, 15, 19, 20, 24, 25, 26, 29, 30, 31, 35, 37, 38, 41, 42, 43, 47, 48, 49, 50, 52, 53, 54, 56, 60, 61, 62, 65 ]
43.939394
false
3.225806
66
9
56.060606
11
def sliders(func, sliders_properties, wait_for_validation=False): n_vars = len(sliders_properties) slider_width = 1.0 / n_vars # CREATE THE CANVAS figure, ax = plt.subplots(1) figure.canvas.set_window_title("Inputs for '%s'" % (func.func_name)) # choose an appropriate height width, height = figure.get_size_inches() height = min(0.5 * n_vars, 8) figure.set_size_inches(width, height, forward=True) # hide the axis ax.set_frame_on(False) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # CREATE THE SLIDERS sliders = [] for i, properties in enumerate(sliders_properties): ax = plt.axes( [0.1, 0.95 - 0.9 * (i + 1) * slider_width, 0.8, 0.8 * slider_width] ) if not isinstance(properties, dict): properties = dict(zip(["label", "valmin", "valmax", "valinit"], properties)) sliders.append(Slider(ax=ax, **properties)) # CREATE THE CALLBACK FUNCTIONS def on_changed(event): res = func(*(s.val for s in sliders)) if res is not None: print(res) def on_key_press(event): if event.key == "enter": on_changed(event) figure.canvas.mpl_connect("key_press_event", on_key_press) # AUTOMATIC UPDATE ? if not wait_for_validation: for s in sliders: s.on_changed(on_changed) # DISPLAY THE SLIDERS plt.show()
28,523
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/VideoFileClip.py
VideoFileClip.__init__
( self, filename, decode_file=False, has_mask=False, audio=True, audio_buffersize=200000, target_resolution=None, resize_algorithm="bicubic", audio_fps=44100, audio_nbytes=2, fps_source="fps", pixel_format=None, )
85
148
def __init__( self, filename, decode_file=False, has_mask=False, audio=True, audio_buffersize=200000, target_resolution=None, resize_algorithm="bicubic", audio_fps=44100, audio_nbytes=2, fps_source="fps", pixel_format=None, ): VideoClip.__init__(self) # Make a reader if not pixel_format: pixel_format = "rgba" if has_mask else "rgb24" self.reader = FFMPEG_VideoReader( filename, decode_file=decode_file, pixel_format=pixel_format, target_resolution=target_resolution, resize_algo=resize_algorithm, fps_source=fps_source, ) # Make some of the reader's attributes accessible from the clip self.duration = self.reader.duration self.end = self.reader.duration self.fps = self.reader.fps self.size = self.reader.size self.rotation = self.reader.rotation self.filename = filename if has_mask: self.make_frame = lambda t: self.reader.get_frame(t)[:, :, :3] def mask_make_frame(t): return self.reader.get_frame(t)[:, :, 3] / 255.0 self.mask = VideoClip( is_mask=True, make_frame=mask_make_frame ).with_duration(self.duration) self.mask.fps = self.fps else: self.make_frame = lambda t: self.reader.get_frame(t) # Make a reader for the audio, if any. if audio and self.reader.infos["audio_found"]: self.audio = AudioFileClip( filename, buffersize=audio_buffersize, fps=audio_fps, nbytes=audio_nbytes, )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/VideoFileClip.py#L85-L148
46
[ 0, 14, 15, 16, 17, 18, 19, 20, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 49, 50, 52, 53, 54, 55, 56, 57, 58 ]
54.6875
[]
0
false
100
64
6
100
0
def __init__( self, filename, decode_file=False, has_mask=False, audio=True, audio_buffersize=200000, target_resolution=None, resize_algorithm="bicubic", audio_fps=44100, audio_nbytes=2, fps_source="fps", pixel_format=None, ): VideoClip.__init__(self) # Make a reader if not pixel_format: pixel_format = "rgba" if has_mask else "rgb24" self.reader = FFMPEG_VideoReader( filename, decode_file=decode_file, pixel_format=pixel_format, target_resolution=target_resolution, resize_algo=resize_algorithm, fps_source=fps_source, ) # Make some of the reader's attributes accessible from the clip self.duration = self.reader.duration self.end = self.reader.duration self.fps = self.reader.fps self.size = self.reader.size self.rotation = self.reader.rotation self.filename = filename if has_mask: self.make_frame = lambda t: self.reader.get_frame(t)[:, :, :3] def mask_make_frame(t): return self.reader.get_frame(t)[:, :, 3] / 255.0 self.mask = VideoClip( is_mask=True, make_frame=mask_make_frame ).with_duration(self.duration) self.mask.fps = self.fps else: self.make_frame = lambda t: self.reader.get_frame(t) # Make a reader for the audio, if any. if audio and self.reader.infos["audio_found"]: self.audio = AudioFileClip( filename, buffersize=audio_buffersize, fps=audio_fps, nbytes=audio_nbytes, )
28,524
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/VideoFileClip.py
VideoFileClip.__deepcopy__
(self, memo)
return self.__copy__()
Implements ``copy.deepcopy(clip)`` behaviour as ``copy.copy(clip)``. VideoFileClip class instances can't be deeply copied because the locked Thread of ``proc`` isn't pickleable. Without this override, calls to ``copy.deepcopy(clip)`` would raise a ``TypeError``: ``` TypeError: cannot pickle '_thread.lock' object ```
Implements ``copy.deepcopy(clip)`` behaviour as ``copy.copy(clip)``.
150
161
def __deepcopy__(self, memo): """Implements ``copy.deepcopy(clip)`` behaviour as ``copy.copy(clip)``. VideoFileClip class instances can't be deeply copied because the locked Thread of ``proc`` isn't pickleable. Without this override, calls to ``copy.deepcopy(clip)`` would raise a ``TypeError``: ``` TypeError: cannot pickle '_thread.lock' object ``` """ return self.__copy__()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/VideoFileClip.py#L150-L161
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
100
12
1
100
9
def __deepcopy__(self, memo): return self.__copy__()
28,525
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/VideoFileClip.py
VideoFileClip.close
(self)
Close the internal reader.
Close the internal reader.
163
174
def close(self): """Close the internal reader.""" if self.reader: self.reader.close() self.reader = None try: if self.audio: self.audio.close() self.audio = None except AttributeError: # pragma: no cover pass
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/VideoFileClip.py#L163-L174
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
120
[]
0
true
100
12
4
100
1
def close(self): if self.reader: self.reader.close() self.reader = None try: if self.audio: self.audio.close() self.audio = None except AttributeError: # pragma: no cover pass
28,526
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/gif_writers.py
write_gif_with_tempfiles
( clip, filename, fps=None, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, pixel_format=None, logger="bar", )
Write the VideoClip to a GIF file. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Does the same as write_gif (see this one for more docstring), but writes every frame to a file instead of passing them in the RAM. Useful on computers with little RAM. Parameters ---------- clip : moviepy.video.VideoClip.VideoClip The clip from which the frames will be extracted to create the GIF image. filename : str Name of the resulting gif file. fps : int, optional Number of frames per second. If it isn't provided, then the function will look for the clip's ``fps`` attribute. program : str, optional Software to use for the conversion, either ``"ImageMagick"`` or ``"ffmpeg"``. opt : str, optional ImageMagick only optimalization to apply, either ``"optimizeplus"`` or ``"OptimizeTransparency"``. Doesn't takes effect if ``program="ffmpeg"``. fuzz : float, optional ImageMagick only compression option which compresses the GIF by considering that the colors that are less than ``fuzz`` different are in fact the same. loop : int, optional Repeat the clip using ``loop`` iterations in the resulting GIF. dispose : bool, optional ImageMagick only option which, when enabled, the ImageMagick binary will take the argument `-dispose 2`, clearing the frame area with the background color, otherwise it will be defined as ``-dispose 1`` which will not dispose, just overlays next frame image. colors : int, optional ImageMagick only option for color reduction. Defines the maximum number of colors that the output image will have. pixel_format : str, optional FFmpeg pixel format for the output gif file. If is not specified ``"rgb24"`` will be used as the default format unless ``clip.mask`` exist, then ``"rgba"`` will be used. Doesn't takes effect if ``program="ImageMagick"``. logger : str, optional Either ``"bar"`` for progress bar or ``None`` or any Proglog logger.
Write the VideoClip to a GIF file.
25
187
def write_gif_with_tempfiles( clip, filename, fps=None, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, pixel_format=None, logger="bar", ): """Write the VideoClip to a GIF file. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Does the same as write_gif (see this one for more docstring), but writes every frame to a file instead of passing them in the RAM. Useful on computers with little RAM. Parameters ---------- clip : moviepy.video.VideoClip.VideoClip The clip from which the frames will be extracted to create the GIF image. filename : str Name of the resulting gif file. fps : int, optional Number of frames per second. If it isn't provided, then the function will look for the clip's ``fps`` attribute. program : str, optional Software to use for the conversion, either ``"ImageMagick"`` or ``"ffmpeg"``. opt : str, optional ImageMagick only optimalization to apply, either ``"optimizeplus"`` or ``"OptimizeTransparency"``. Doesn't takes effect if ``program="ffmpeg"``. fuzz : float, optional ImageMagick only compression option which compresses the GIF by considering that the colors that are less than ``fuzz`` different are in fact the same. loop : int, optional Repeat the clip using ``loop`` iterations in the resulting GIF. dispose : bool, optional ImageMagick only option which, when enabled, the ImageMagick binary will take the argument `-dispose 2`, clearing the frame area with the background color, otherwise it will be defined as ``-dispose 1`` which will not dispose, just overlays next frame image. colors : int, optional ImageMagick only option for color reduction. Defines the maximum number of colors that the output image will have. pixel_format : str, optional FFmpeg pixel format for the output gif file. If is not specified ``"rgb24"`` will be used as the default format unless ``clip.mask`` exist, then ``"rgba"`` will be used. Doesn't takes effect if ``program="ImageMagick"``. logger : str, optional Either ``"bar"`` for progress bar or ``None`` or any Proglog logger. """ logger = proglog.default_bar_logger(logger) file_root, ext = os.path.splitext(filename) tt = np.arange(0, clip.duration, 1.0 / fps) tempfiles = [] logger(message="MoviePy - Building file %s\n" % filename) logger(message="MoviePy - - Generating GIF frames") for i, t in logger.iter_bar(t=list(enumerate(tt))): name = "%s_GIFTEMP%04d.png" % (file_root, i + 1) tempfiles.append(name) clip.save_frame(name, t, with_mask=True) delay = int(100.0 / fps) if clip.mask is None: with_mask = False if program == "ImageMagick": if not pixel_format: pixel_format = "RGBA" if with_mask else "RGB" logger(message="MoviePy - - Optimizing GIF with ImageMagick...") cmd = ( [ IMAGEMAGICK_BINARY, "-delay", "%d" % delay, "-dispose", "%d" % (2 if dispose else 1), "-loop", "%d" % loop, "%s_GIFTEMP*.png" % file_root, "-coalesce", "-fuzz", "%02d" % fuzz + "%", "-layers", "%s" % opt, "-set", "colorspace", pixel_format, ] + (["-colors", "%d" % colors] if colors is not None else []) + [filename] ) elif program == "ffmpeg": if loop: clip = loop_fx(clip, n=loop) if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" cmd = [ FFMPEG_BINARY, "-y", "-f", "image2", "-r", str(fps), "-i", file_root + "_GIFTEMP%04d.png", "-r", str(fps), filename, "-pix_fmt", (pixel_format), ] try: subprocess_call(cmd, logger=logger) logger(message="MoviePy - GIF ready: %s." % filename) except (IOError, OSError) as err: error = ( "MoviePy Error: creation of %s failed because " "of the following error:\n\n%s.\n\n." % (filename, str(err)) ) if program == "ImageMagick": error += ( "This error can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary. Check the documentation." ) raise IOError(error) for file in tempfiles: os.remove(file)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/gif_writers.py#L25-L187
46
[ 0, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 160, 161, 162 ]
32.515337
[ 90, 91, 93, 94, 119, 144, 146, 151, 152, 159 ]
6.134969
false
68.067227
163
11
93.865031
55
def write_gif_with_tempfiles( clip, filename, fps=None, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, pixel_format=None, logger="bar", ): logger = proglog.default_bar_logger(logger) file_root, ext = os.path.splitext(filename) tt = np.arange(0, clip.duration, 1.0 / fps) tempfiles = [] logger(message="MoviePy - Building file %s\n" % filename) logger(message="MoviePy - - Generating GIF frames") for i, t in logger.iter_bar(t=list(enumerate(tt))): name = "%s_GIFTEMP%04d.png" % (file_root, i + 1) tempfiles.append(name) clip.save_frame(name, t, with_mask=True) delay = int(100.0 / fps) if clip.mask is None: with_mask = False if program == "ImageMagick": if not pixel_format: pixel_format = "RGBA" if with_mask else "RGB" logger(message="MoviePy - - Optimizing GIF with ImageMagick...") cmd = ( [ IMAGEMAGICK_BINARY, "-delay", "%d" % delay, "-dispose", "%d" % (2 if dispose else 1), "-loop", "%d" % loop, "%s_GIFTEMP*.png" % file_root, "-coalesce", "-fuzz", "%02d" % fuzz + "%", "-layers", "%s" % opt, "-set", "colorspace", pixel_format, ] + (["-colors", "%d" % colors] if colors is not None else []) + [filename] ) elif program == "ffmpeg": if loop: clip = loop_fx(clip, n=loop) if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" cmd = [ FFMPEG_BINARY, "-y", "-f", "image2", "-r", str(fps), "-i", file_root + "_GIFTEMP%04d.png", "-r", str(fps), filename, "-pix_fmt", (pixel_format), ] try: subprocess_call(cmd, logger=logger) logger(message="MoviePy - GIF ready: %s." % filename) except (IOError, OSError) as err: error = ( "MoviePy Error: creation of %s failed because " "of the following error:\n\n%s.\n\n." % (filename, str(err)) ) if program == "ImageMagick": error += ( "This error can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary. Check the documentation." ) raise IOError(error) for file in tempfiles: os.remove(file)
28,527
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/gif_writers.py
write_gif
( clip, filename, fps=None, with_mask=True, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, pixel_format=None, logger="bar", )
Write the VideoClip to a GIF file, without temporary files. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Parameters ---------- clip : moviepy.video.VideoClip.VideoClip The clip from which the frames will be extracted to create the GIF image. filename : str Name of the resulting gif file. fps : int, optional Number of frames per second. If it isn't provided, then the function will look for the clip's ``fps`` attribute. with_mask : bool, optional Includes the mask of the clip in the output (the clip must have a mask if this argument is ``True``). program : str, optional Software to use for the conversion, either ``"ImageMagick"`` or ``"ffmpeg"``. opt : str, optional ImageMagick only optimalization to apply, either ``"optimizeplus"`` or ``"OptimizeTransparency"``. Doesn't takes effect if ``program="ffmpeg"``. fuzz : float, optional ImageMagick only compression option which compresses the GIF by considering that the colors that are less than ``fuzz`` different are in fact the same. loop : int, optional Repeat the clip using ``loop`` iterations in the resulting GIF. dispose : bool, optional ImageMagick only option which, when enabled, the ImageMagick binary will take the argument `-dispose 2`, clearing the frame area with the background color, otherwise it will be defined as ``-dispose 1`` which will not dispose, just overlays next frame image. colors : int, optional ImageMagick only option for color reduction. Defines the maximum number of colors that the output image will have. pixel_format : str, optional FFmpeg pixel format for the output gif file. If is not specified ``"rgb24"`` will be used as the default format unless ``clip.mask`` exist, then ``"rgba"`` will be used. Doesn't takes effect if ``program="ImageMagick"``. logger : str, optional Either ``"bar"`` for progress bar or ``None`` or any Proglog logger. Examples -------- The gif will be playing the clip in real time, you can only change the frame rate. If you want the gif to be played slower than the clip you will use: >>> # slow down clip 50% and make it a GIF >>> myClip.multiply_speed(0.5).write_gif('myClip.gif')
Write the VideoClip to a GIF file, without temporary files.
192
425
def write_gif( clip, filename, fps=None, with_mask=True, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, pixel_format=None, logger="bar", ): """Write the VideoClip to a GIF file, without temporary files. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. Parameters ---------- clip : moviepy.video.VideoClip.VideoClip The clip from which the frames will be extracted to create the GIF image. filename : str Name of the resulting gif file. fps : int, optional Number of frames per second. If it isn't provided, then the function will look for the clip's ``fps`` attribute. with_mask : bool, optional Includes the mask of the clip in the output (the clip must have a mask if this argument is ``True``). program : str, optional Software to use for the conversion, either ``"ImageMagick"`` or ``"ffmpeg"``. opt : str, optional ImageMagick only optimalization to apply, either ``"optimizeplus"`` or ``"OptimizeTransparency"``. Doesn't takes effect if ``program="ffmpeg"``. fuzz : float, optional ImageMagick only compression option which compresses the GIF by considering that the colors that are less than ``fuzz`` different are in fact the same. loop : int, optional Repeat the clip using ``loop`` iterations in the resulting GIF. dispose : bool, optional ImageMagick only option which, when enabled, the ImageMagick binary will take the argument `-dispose 2`, clearing the frame area with the background color, otherwise it will be defined as ``-dispose 1`` which will not dispose, just overlays next frame image. colors : int, optional ImageMagick only option for color reduction. Defines the maximum number of colors that the output image will have. pixel_format : str, optional FFmpeg pixel format for the output gif file. If is not specified ``"rgb24"`` will be used as the default format unless ``clip.mask`` exist, then ``"rgba"`` will be used. Doesn't takes effect if ``program="ImageMagick"``. logger : str, optional Either ``"bar"`` for progress bar or ``None`` or any Proglog logger. Examples -------- The gif will be playing the clip in real time, you can only change the frame rate. If you want the gif to be played slower than the clip you will use: >>> # slow down clip 50% and make it a GIF >>> myClip.multiply_speed(0.5).write_gif('myClip.gif') """ # # We use processes chained with pipes. # # if program == 'ffmpeg' # frames --ffmpeg--> gif # # if program == 'ImageMagick' and optimize == (None, False) # frames --ffmpeg--> bmp frames --ImageMagick--> gif # # # if program == 'ImageMagick' and optimize != (None, False) # frames -ffmpeg-> bmp frames -ImagMag-> gif -ImagMag-> better gif # delay = 100.0 / fps logger = proglog.default_bar_logger(logger) if clip.mask is None: with_mask = False if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" cmd1 = [ FFMPEG_BINARY, "-y", "-loglevel", "error", "-f", "rawvideo", "-vcodec", "rawvideo", "-r", "%.02f" % fps, "-s", "%dx%d" % (clip.w, clip.h), "-pix_fmt", (pixel_format), "-i", "-", ] popen_params = cross_platform_popen_params( {"stdout": sp.DEVNULL, "stderr": sp.DEVNULL, "stdin": sp.DEVNULL} ) if program == "ffmpeg": if loop: clip = loop_fx(clip, n=loop) popen_params["stdin"] = sp.PIPE popen_params["stdout"] = sp.DEVNULL proc1 = sp.Popen( cmd1 + [ "-pix_fmt", (pixel_format), "-r", "%.02f" % fps, filename, ], **popen_params, ) else: popen_params["stdin"] = sp.PIPE popen_params["stdout"] = sp.PIPE proc1 = sp.Popen( cmd1 + ["-f", "image2pipe", "-vcodec", "bmp", "-"], **popen_params ) if program == "ImageMagick": cmd2 = [ IMAGEMAGICK_BINARY, "-delay", "%.02f" % (delay), "-dispose", "%d" % (2 if dispose else 1), "-loop", "%d" % loop, "-", "-coalesce", ] if opt in [False, None]: popen_params["stdin"] = proc1.stdout popen_params["stdout"] = sp.DEVNULL proc2 = sp.Popen(cmd2 + [filename], **popen_params) else: popen_params["stdin"] = proc1.stdout popen_params["stdout"] = sp.PIPE proc2 = sp.Popen(cmd2 + ["gif:-"], **popen_params) if opt: cmd3 = ( [ IMAGEMAGICK_BINARY, "-", "-fuzz", "%d" % fuzz + "%", "-layers", opt, ] + (["-colors", "%d" % colors] if colors is not None else []) + [filename] ) popen_params["stdin"] = proc2.stdout popen_params["stdout"] = sp.DEVNULL proc3 = sp.Popen(cmd3, **popen_params) # We send all the frames to the first process logger(message="MoviePy - Building file %s" % filename) logger(message="MoviePy - - Generating GIF frames.") try: for t, frame in clip.iter_frames( fps=fps, logger=logger, with_times=True, dtype="uint8" ): if with_mask: mask = 255 * clip.mask.get_frame(t) frame = np.dstack([frame, mask]).astype("uint8") proc1.stdin.write(frame.tobytes()) except IOError as err: error = ( "[MoviePy] Error: creation of %s failed because " "of the following error:\n\n%s.\n\n." % (filename, str(err)) ) if program == "ImageMagick": error += ( "This can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary. Check the documentation." ) raise IOError(error) if program == "ImageMagick": logger(message="MoviePy - - Optimizing GIF with ImageMagick.") proc1.stdin.close() proc1.wait() if program == "ImageMagick": proc2.wait() if opt: proc3.wait() logger(message="MoviePy - - File ready: %s." % filename)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/gif_writers.py#L192-L425
46
[ 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 122, 123, 126, 127, 128, 129, 130, 131, 132, 133, 134, 153, 154, 155, 197, 198, 199, 200, 201, 204, 205, 206, 207, 208, 225, 227, 228, 229, 233 ]
16.666667
[ 147, 148, 150, 156, 168, 169, 170, 171, 174, 175, 176, 178, 180, 193, 194, 195, 209, 211, 216, 217, 224, 226, 230, 231, 232 ]
10.683761
false
68.067227
234
15
89.316239
68
def write_gif( clip, filename, fps=None, with_mask=True, program="ImageMagick", opt="OptimizeTransparency", fuzz=1, loop=0, dispose=True, colors=None, pixel_format=None, logger="bar", ): # # We use processes chained with pipes. # # if program == 'ffmpeg' # frames --ffmpeg--> gif # # if program == 'ImageMagick' and optimize == (None, False) # frames --ffmpeg--> bmp frames --ImageMagick--> gif # # # if program == 'ImageMagick' and optimize != (None, False) # frames -ffmpeg-> bmp frames -ImagMag-> gif -ImagMag-> better gif # delay = 100.0 / fps logger = proglog.default_bar_logger(logger) if clip.mask is None: with_mask = False if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" cmd1 = [ FFMPEG_BINARY, "-y", "-loglevel", "error", "-f", "rawvideo", "-vcodec", "rawvideo", "-r", "%.02f" % fps, "-s", "%dx%d" % (clip.w, clip.h), "-pix_fmt", (pixel_format), "-i", "-", ] popen_params = cross_platform_popen_params( {"stdout": sp.DEVNULL, "stderr": sp.DEVNULL, "stdin": sp.DEVNULL} ) if program == "ffmpeg": if loop: clip = loop_fx(clip, n=loop) popen_params["stdin"] = sp.PIPE popen_params["stdout"] = sp.DEVNULL proc1 = sp.Popen( cmd1 + [ "-pix_fmt", (pixel_format), "-r", "%.02f" % fps, filename, ], **popen_params, ) else: popen_params["stdin"] = sp.PIPE popen_params["stdout"] = sp.PIPE proc1 = sp.Popen( cmd1 + ["-f", "image2pipe", "-vcodec", "bmp", "-"], **popen_params ) if program == "ImageMagick": cmd2 = [ IMAGEMAGICK_BINARY, "-delay", "%.02f" % (delay), "-dispose", "%d" % (2 if dispose else 1), "-loop", "%d" % loop, "-", "-coalesce", ] if opt in [False, None]: popen_params["stdin"] = proc1.stdout popen_params["stdout"] = sp.DEVNULL proc2 = sp.Popen(cmd2 + [filename], **popen_params) else: popen_params["stdin"] = proc1.stdout popen_params["stdout"] = sp.PIPE proc2 = sp.Popen(cmd2 + ["gif:-"], **popen_params) if opt: cmd3 = ( [ IMAGEMAGICK_BINARY, "-", "-fuzz", "%d" % fuzz + "%", "-layers", opt, ] + (["-colors", "%d" % colors] if colors is not None else []) + [filename] ) popen_params["stdin"] = proc2.stdout popen_params["stdout"] = sp.DEVNULL proc3 = sp.Popen(cmd3, **popen_params) # We send all the frames to the first process logger(message="MoviePy - Building file %s" % filename) logger(message="MoviePy - - Generating GIF frames.") try: for t, frame in clip.iter_frames( fps=fps, logger=logger, with_times=True, dtype="uint8" ): if with_mask: mask = 255 * clip.mask.get_frame(t) frame = np.dstack([frame, mask]).astype("uint8") proc1.stdin.write(frame.tobytes()) except IOError as err: error = ( "[MoviePy] Error: creation of %s failed because " "of the following error:\n\n%s.\n\n." % (filename, str(err)) ) if program == "ImageMagick": error += ( "This can be due to the fact that " "ImageMagick is not installed on your computer, or " "(for Windows users) that you didn't specify the " "path to the ImageMagick binary. Check the documentation." ) raise IOError(error) if program == "ImageMagick": logger(message="MoviePy - - Optimizing GIF with ImageMagick.") proc1.stdin.close() proc1.wait() if program == "ImageMagick": proc2.wait() if opt: proc3.wait() logger(message="MoviePy - - File ready: %s." % filename)
28,528
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/gif_writers.py
write_gif_with_image_io
( clip, filename, fps=None, opt=0, loop=0, colors=None, logger="bar" )
Writes the gif with the Python library ImageIO (calls FreeImage).
Writes the gif with the Python library ImageIO (calls FreeImage).
428
454
def write_gif_with_image_io( clip, filename, fps=None, opt=0, loop=0, colors=None, logger="bar" ): """Writes the gif with the Python library ImageIO (calls FreeImage).""" if colors is None: colors = 256 logger = proglog.default_bar_logger(logger) if not IMAGEIO_FOUND: raise ImportError( "Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'" ) if fps is None: fps = clip.fps quantizer = 0 if opt != 0 else "nq" writer = imageio.save( filename, duration=1.0 / fps, quantizer=quantizer, palettesize=colors, loop=loop ) logger(message="MoviePy - Building file %s with imageio." % filename) for frame in clip.iter_frames(fps=fps, logger=logger, dtype="uint8"): writer.append_data(frame)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/gif_writers.py#L428-L454
46
[ 0, 3, 4, 5, 6, 7, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]
77.777778
[ 9 ]
3.703704
false
68.067227
27
5
96.296296
1
def write_gif_with_image_io( clip, filename, fps=None, opt=0, loop=0, colors=None, logger="bar" ): if colors is None: colors = 256 logger = proglog.default_bar_logger(logger) if not IMAGEIO_FOUND: raise ImportError( "Writing a gif with imageio requires ImageIO installed," " with e.g. 'pip install imageio'" ) if fps is None: fps = clip.fps quantizer = 0 if opt != 0 else "nq" writer = imageio.save( filename, duration=1.0 / fps, quantizer=quantizer, palettesize=colors, loop=loop ) logger(message="MoviePy - Building file %s with imageio." % filename) for frame in clip.iter_frames(fps=fps, logger=logger, dtype="uint8"): writer.append_data(frame)
28,529
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ImageSequenceClip.py
ImageSequenceClip.__init__
( self, sequence, fps=None, durations=None, with_mask=True, is_mask=False, load_images=False, )
43
166
def __init__( self, sequence, fps=None, durations=None, with_mask=True, is_mask=False, load_images=False, ): # CODE WRITTEN AS IT CAME, MAY BE IMPROVED IN THE FUTURE if (fps is None) and (durations is None): raise ValueError("Please provide either 'fps' or 'durations'.") VideoClip.__init__(self, is_mask=is_mask) # Parse the data fromfiles = True if isinstance(sequence, list): if isinstance(sequence[0], str): if load_images: sequence = [imread(file) for file in sequence] fromfiles = False else: fromfiles = True else: # sequence is already a list of numpy arrays fromfiles = False else: # sequence is a folder name, make it a list of files: fromfiles = True sequence = sorted( [os.path.join(sequence, file) for file in os.listdir(sequence)] ) # check that all the images are of the same size if isinstance(sequence[0], str): size = imread(sequence[0]).shape else: size = sequence[0].shape for image in sequence: image1 = image if isinstance(image, str): image1 = imread(image) if size != image1.shape: raise Exception( "Moviepy: ImageSequenceClip requires all images to be the same size" ) self.fps = fps if fps is not None: durations = [1.0 / fps for image in sequence] self.images_starts = [ 1.0 * i / fps - np.finfo(np.float32).eps for i in range(len(sequence)) ] else: self.images_starts = [0] + list(np.cumsum(durations)) self.durations = durations self.duration = sum(durations) self.end = self.duration self.sequence = sequence def find_image_index(t): return max( [i for i in range(len(self.sequence)) if self.images_starts[i] <= t] ) if fromfiles: self.last_index = None self.last_image = None def make_frame(t): index = find_image_index(t) if index != self.last_index: self.last_image = imread(self.sequence[index])[:, :, :3] self.last_index = index return self.last_image if with_mask and (imread(self.sequence[0]).shape[2] == 4): self.mask = VideoClip(is_mask=True) self.mask.last_index = None self.mask.last_image = None def mask_make_frame(t): index = find_image_index(t) if index != self.mask.last_index: frame = imread(self.sequence[index])[:, :, 3] self.mask.last_image = frame.astype(float) / 255 self.mask.last_index = index return self.mask.last_image self.mask.make_frame = mask_make_frame self.mask.size = mask_make_frame(0).shape[:2][::-1] else: def make_frame(t): index = find_image_index(t) return self.sequence[index][:, :, :3] if with_mask and (self.sequence[0].shape[2] == 4): self.mask = VideoClip(is_mask=True) def mask_make_frame(t): index = find_image_index(t) return 1.0 * self.sequence[index][:, :, 3] / 255 self.mask.make_frame = mask_make_frame self.mask.size = mask_make_frame(0).shape[:2][::-1] self.make_frame = make_frame self.size = make_frame(0).shape[:2][::-1]
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ImageSequenceClip.py#L43-L166
46
[ 0, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 26, 37, 38, 39, 42, 43, 44, 45, 46, 47, 48, 51, 52, 53, 59, 60, 61, 62, 63, 64, 65, 66, 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, 121, 122, 123 ]
58.064516
[ 13, 23, 24, 29, 32, 33, 41, 54, 55, 106, 108, 109, 111, 113, 115, 116, 117, 119, 120 ]
15.322581
false
73.972603
124
28
84.677419
0
def __init__( self, sequence, fps=None, durations=None, with_mask=True, is_mask=False, load_images=False, ): # CODE WRITTEN AS IT CAME, MAY BE IMPROVED IN THE FUTURE if (fps is None) and (durations is None): raise ValueError("Please provide either 'fps' or 'durations'.") VideoClip.__init__(self, is_mask=is_mask) # Parse the data fromfiles = True if isinstance(sequence, list): if isinstance(sequence[0], str): if load_images: sequence = [imread(file) for file in sequence] fromfiles = False else: fromfiles = True else: # sequence is already a list of numpy arrays fromfiles = False else: # sequence is a folder name, make it a list of files: fromfiles = True sequence = sorted( [os.path.join(sequence, file) for file in os.listdir(sequence)] ) # check that all the images are of the same size if isinstance(sequence[0], str): size = imread(sequence[0]).shape else: size = sequence[0].shape for image in sequence: image1 = image if isinstance(image, str): image1 = imread(image) if size != image1.shape: raise Exception( "Moviepy: ImageSequenceClip requires all images to be the same size" ) self.fps = fps if fps is not None: durations = [1.0 / fps for image in sequence] self.images_starts = [ 1.0 * i / fps - np.finfo(np.float32).eps for i in range(len(sequence)) ] else: self.images_starts = [0] + list(np.cumsum(durations)) self.durations = durations self.duration = sum(durations) self.end = self.duration self.sequence = sequence def find_image_index(t): return max( [i for i in range(len(self.sequence)) if self.images_starts[i] <= t] ) if fromfiles: self.last_index = None self.last_image = None def make_frame(t): index = find_image_index(t) if index != self.last_index: self.last_image = imread(self.sequence[index])[:, :, :3] self.last_index = index return self.last_image if with_mask and (imread(self.sequence[0]).shape[2] == 4): self.mask = VideoClip(is_mask=True) self.mask.last_index = None self.mask.last_image = None def mask_make_frame(t): index = find_image_index(t) if index != self.mask.last_index: frame = imread(self.sequence[index])[:, :, 3] self.mask.last_image = frame.astype(float) / 255 self.mask.last_index = index return self.mask.last_image self.mask.make_frame = mask_make_frame self.mask.size = mask_make_frame(0).shape[:2][::-1] else: def make_frame(t): index = find_image_index(t) return self.sequence[index][:, :, :3] if with_mask and (self.sequence[0].shape[2] == 4): self.mask = VideoClip(is_mask=True) def mask_make_frame(t): index = find_image_index(t) return 1.0 * self.sequence[index][:, :, 3] / 255 self.mask.make_frame = mask_make_frame self.mask.size = mask_make_frame(0).shape[:2][::-1] self.make_frame = make_frame self.size = make_frame(0).shape[:2][::-1]
28,530
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/preview.py
imdisplay
(imarray, screen=None)
Splashes the given image array on the given pygame screen.
Splashes the given image array on the given pygame screen.
21
27
def imdisplay(imarray, screen=None): """Splashes the given image array on the given pygame screen.""" a = pg.surfarray.make_surface(imarray.swapaxes(0, 1)) if screen is None: screen = pg.display.set_mode(imarray.shape[:2][::-1]) screen.blit(a, (0, 0)) pg.display.flip()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/preview.py#L21-L27
46
[]
0
[ 0, 2, 3, 4, 5, 6 ]
85.714286
false
5.479452
7
2
14.285714
1
def imdisplay(imarray, screen=None): a = pg.surfarray.make_surface(imarray.swapaxes(0, 1)) if screen is None: screen = pg.display.set_mode(imarray.shape[:2][::-1]) screen.blit(a, (0, 0)) pg.display.flip()
28,531
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/preview.py
show
(clip, t=0, with_mask=True, interactive=False)
Splashes the frame of clip corresponding to time ``t``. Parameters ---------- t : float or tuple or str, optional Time in seconds of the frame to display. with_mask : bool, optional ``False`` if the clip has a mask but you want to see the clip without the mask. interactive : bool, optional Displays the image freezed and you can clip in each pixel to see the pixel number and its color. Examples -------- >>> from moviepy.editor import * >>> >>> clip = VideoFileClip("media/chaplin.mp4") >>> clip.show(t=4, interactive=True)
Splashes the frame of clip corresponding to time ``t``.
32
77
def show(clip, t=0, with_mask=True, interactive=False): """ Splashes the frame of clip corresponding to time ``t``. Parameters ---------- t : float or tuple or str, optional Time in seconds of the frame to display. with_mask : bool, optional ``False`` if the clip has a mask but you want to see the clip without the mask. interactive : bool, optional Displays the image freezed and you can clip in each pixel to see the pixel number and its color. Examples -------- >>> from moviepy.editor import * >>> >>> clip = VideoFileClip("media/chaplin.mp4") >>> clip.show(t=4, interactive=True) """ if with_mask and (clip.mask is not None): clip = CompositeVideoClip([clip.with_position((0, 0))]) img = clip.get_frame(t) imdisplay(img) if interactive: result = [] while True: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: print("Keyboard interrupt") return result elif event.type == pg.MOUSEBUTTONDOWN: x, y = pg.mouse.get_pos() rgb = img[y, x] result.append({"position": (x, y), "color": rgb}) print("position, color : ", "%s, %s" % (str((x, y)), str(rgb))) time.sleep(0.03)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/preview.py#L32-L77
46
[]
0
[ 0, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 ]
41.304348
false
5.479452
46
9
58.695652
23
def show(clip, t=0, with_mask=True, interactive=False): if with_mask and (clip.mask is not None): clip = CompositeVideoClip([clip.with_position((0, 0))]) img = clip.get_frame(t) imdisplay(img) if interactive: result = [] while True: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: print("Keyboard interrupt") return result elif event.type == pg.MOUSEBUTTONDOWN: x, y = pg.mouse.get_pos() rgb = img[y, x] result.append({"position": (x, y), "color": rgb}) print("position, color : ", "%s, %s" % (str((x, y)), str(rgb))) time.sleep(0.03)
28,532
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/preview.py
preview
( clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000, audio_nbytes=2, fullscreen=False, )
Displays the clip in a window, at the given frames per second (of movie) rate. It will avoid that the clip be played faster than normal, but it cannot avoid the clip to be played slower than normal if the computations are complex. In this case, try reducing the ``fps``. Parameters ---------- fps : int, optional Number of frames per seconds in the displayed video. audio : bool, optional ``True`` (default) if you want the clip's audio be played during the preview. audio_fps : int, optional The frames per second to use when generating the audio sound. audio_buffersize : int, optional The sized of the buffer used generating the audio sound. audio_nbytes : int, optional The number of bytes used generating the audio sound. fullscreen : bool, optional ``True`` if you want the preview to be displayed fullscreen. Examples -------- >>> from moviepy.editor import * >>> >>> clip = VideoFileClip("media/chaplin.mp4") >>> clip.preview(fps=10, audio=False)
Displays the clip in a window, at the given frames per second (of movie) rate. It will avoid that the clip be played faster than normal, but it cannot avoid the clip to be played slower than normal if the computations are complex. In this case, try reducing the ``fps``.
82
188
def preview( clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000, audio_nbytes=2, fullscreen=False, ): """ Displays the clip in a window, at the given frames per second (of movie) rate. It will avoid that the clip be played faster than normal, but it cannot avoid the clip to be played slower than normal if the computations are complex. In this case, try reducing the ``fps``. Parameters ---------- fps : int, optional Number of frames per seconds in the displayed video. audio : bool, optional ``True`` (default) if you want the clip's audio be played during the preview. audio_fps : int, optional The frames per second to use when generating the audio sound. audio_buffersize : int, optional The sized of the buffer used generating the audio sound. audio_nbytes : int, optional The number of bytes used generating the audio sound. fullscreen : bool, optional ``True`` if you want the preview to be displayed fullscreen. Examples -------- >>> from moviepy.editor import * >>> >>> clip = VideoFileClip("media/chaplin.mp4") >>> clip.preview(fps=10, audio=False) """ if fullscreen: flags = pg.FULLSCREEN else: flags = 0 # compute and splash the first image screen = pg.display.set_mode(clip.size, flags) audio = audio and (clip.audio is not None) if audio: # the sound will be played in parallel. We are not # parralellizing it on different CPUs because it seems that # pygame and openCV already use several cpus it seems. # two synchro-flags to tell whether audio and video are ready video_flag = threading.Event() audio_flag = threading.Event() # launch the thread audiothread = threading.Thread( target=clip.audio.preview, args=(audio_fps, audio_buffersize, audio_nbytes, audio_flag, video_flag), ) audiothread.start() img = clip.get_frame(0) imdisplay(img, screen) if audio: # synchronize with audio video_flag.set() # say to the audio: video is ready audio_flag.wait() # wait for the audio to be ready result = [] t0 = time.time() for t in np.arange(1.0 / fps, clip.duration - 0.001, 1.0 / fps): img = clip.get_frame(t) for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE ): if audio: video_flag.clear() print("Interrupt") pg.quit() return result elif event.type == pg.MOUSEBUTTONDOWN: x, y = pg.mouse.get_pos() rgb = img[y, x] result.append({"time": t, "position": (x, y), "color": rgb}) print( "time, position, color : ", "%.03f, %s, %s" % (t, str((x, y)), str(rgb)), ) t1 = time.time() time.sleep(max(0, t - (t1 - t0))) imdisplay(img, screen) pg.quit()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/preview.py#L82-L188
46
[]
0
[ 0, 45, 46, 48, 51, 53, 55, 61, 62, 64, 68, 70, 71, 72, 73, 74, 76, 78, 79, 81, 83, 84, 87, 88, 89, 90, 91, 93, 94, 95, 96, 97, 102, 103, 104, 106 ]
33.64486
false
5.479452
107
12
66.35514
34
def preview( clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000, audio_nbytes=2, fullscreen=False, ): if fullscreen: flags = pg.FULLSCREEN else: flags = 0 # compute and splash the first image screen = pg.display.set_mode(clip.size, flags) audio = audio and (clip.audio is not None) if audio: # the sound will be played in parallel. We are not # parralellizing it on different CPUs because it seems that # pygame and openCV already use several cpus it seems. # two synchro-flags to tell whether audio and video are ready video_flag = threading.Event() audio_flag = threading.Event() # launch the thread audiothread = threading.Thread( target=clip.audio.preview, args=(audio_fps, audio_buffersize, audio_nbytes, audio_flag, video_flag), ) audiothread.start() img = clip.get_frame(0) imdisplay(img, screen) if audio: # synchronize with audio video_flag.set() # say to the audio: video is ready audio_flag.wait() # wait for the audio to be ready result = [] t0 = time.time() for t in np.arange(1.0 / fps, clip.duration - 0.001, 1.0 / fps): img = clip.get_frame(t) for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE ): if audio: video_flag.clear() print("Interrupt") pg.quit() return result elif event.type == pg.MOUSEBUTTONDOWN: x, y = pg.mouse.get_pos() rgb = img[y, x] result.append({"time": t, "position": (x, y), "color": rgb}) print( "time, position, color : ", "%.03f, %s, %s" % (t, str((x, y)), str(rgb)), ) t1 = time.time() time.sleep(max(0, t - (t1 - t0))) imdisplay(img, screen) pg.quit()
28,533
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/html_tools.py
html_embed
( clip, filetype=None, maxduration=60, rd_kwargs=None, center=True, **html_kwargs )
return result
Returns HTML5 code embedding the clip. Parameters ---------- clip : moviepy.Clip.Clip Either a file name, or a clip to preview. Either an image, a sound or a video. Clips will actually be written to a file and embedded as if a filename was provided. filetype : str, optional One of 'video','image','audio'. If None is given, it is determined based on the extension of ``filename``, but this can bug. maxduration : float, optional An error will be raised if the clip's duration is more than the indicated value (in seconds), to avoid spoiling the browser's cache and the RAM. rd_kwargs : dict, optional Keyword arguments for the rendering, like ``dict(fps=15, bitrate="50k")``. Allow you to give some options to the render process. You can, for example, disable the logger bar passing ``dict(logger=None)``. center : bool, optional If true (default), the content will be wrapped in a ``<div align=middle>`` HTML container, so the content will be displayed at the center. html_kwargs Allow you to give some options, like ``width=260``, ``autoplay=True``, ``loop=1`` etc. Examples -------- >>> from moviepy.editor import * >>> # later ... >>> html_embed(clip, width=360) >>> html_embed(clip.audio) >>> clip.write_gif("test.gif") >>> html_embed('test.gif') >>> clip.save_frame("first_frame.jpeg") >>> html_embed("first_frame.jpeg")
Returns HTML5 code embedding the clip.
54
191
def html_embed( clip, filetype=None, maxduration=60, rd_kwargs=None, center=True, **html_kwargs ): """Returns HTML5 code embedding the clip. Parameters ---------- clip : moviepy.Clip.Clip Either a file name, or a clip to preview. Either an image, a sound or a video. Clips will actually be written to a file and embedded as if a filename was provided. filetype : str, optional One of 'video','image','audio'. If None is given, it is determined based on the extension of ``filename``, but this can bug. maxduration : float, optional An error will be raised if the clip's duration is more than the indicated value (in seconds), to avoid spoiling the browser's cache and the RAM. rd_kwargs : dict, optional Keyword arguments for the rendering, like ``dict(fps=15, bitrate="50k")``. Allow you to give some options to the render process. You can, for example, disable the logger bar passing ``dict(logger=None)``. center : bool, optional If true (default), the content will be wrapped in a ``<div align=middle>`` HTML container, so the content will be displayed at the center. html_kwargs Allow you to give some options, like ``width=260``, ``autoplay=True``, ``loop=1`` etc. Examples -------- >>> from moviepy.editor import * >>> # later ... >>> html_embed(clip, width=360) >>> html_embed(clip.audio) >>> clip.write_gif("test.gif") >>> html_embed('test.gif') >>> clip.save_frame("first_frame.jpeg") >>> html_embed("first_frame.jpeg") """ if rd_kwargs is None: # pragma: no cover rd_kwargs = {} if "Clip" in str(clip.__class__): TEMP_PREFIX = "__temp__" if isinstance(clip, ImageClip): filename = TEMP_PREFIX + ".png" kwargs = {"filename": filename, "with_mask": True} argnames = inspect.getfullargspec(clip.save_frame).args kwargs.update( {key: value for key, value in rd_kwargs.items() if key in argnames} ) clip.save_frame(**kwargs) elif isinstance(clip, VideoClip): filename = TEMP_PREFIX + ".mp4" kwargs = {"filename": filename, "preset": "ultrafast"} kwargs.update(rd_kwargs) clip.write_videofile(**kwargs) elif isinstance(clip, AudioClip): filename = TEMP_PREFIX + ".mp3" kwargs = {"filename": filename} kwargs.update(rd_kwargs) clip.write_audiofile(**kwargs) else: raise ValueError("Unknown class for the clip. Cannot embed and preview.") return html_embed( filename, maxduration=maxduration, rd_kwargs=rd_kwargs, center=center, **html_kwargs, ) filename = clip options = " ".join(["%s='%s'" % (str(k), str(v)) for k, v in html_kwargs.items()]) name, ext = os.path.splitext(filename) ext = ext[1:] if filetype is None: ext = filename.split(".")[-1].lower() if ext == "gif": filetype = "image" elif ext in extensions_dict: filetype = extensions_dict[ext]["type"] else: raise ValueError( "No file type is known for the provided file. Please provide " "argument `filetype` (one of 'image', 'video', 'sound') to the " "ipython display function." ) if filetype == "video": # The next lines set the HTML5-cvompatible extension and check that the # extension is HTML5-valid exts_htmltype = {"mp4": "mp4", "webm": "webm", "ogv": "ogg"} allowed_exts = " ".join(exts_htmltype.keys()) try: ext = exts_htmltype[ext] except Exception: raise ValueError( "This video extension cannot be displayed in the " "IPython Notebook. Allowed extensions: " + allowed_exts ) if filetype in ["audio", "video"]: duration = ffmpeg_parse_infos(filename, decode_file=True)["duration"] if duration > maxduration: raise ValueError( ( "The duration of video %s (%.1f) exceeds the 'maxduration'" " attribute. You can increase 'maxduration', by passing" " 'maxduration' parameter to ipython_display function." " But note that embedding large videos may take all the memory" " away!" ) % (filename, duration) ) with open(filename, "rb") as file: data = b64encode(file.read()).decode("utf-8") template = templates[filetype] result = template % {"data": data, "options": options, "ext": ext} if center: result = r"<div align=middle>%s</div>" % result return result
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/html_tools.py#L54-L191
46
[ 0, 51, 52, 53, 54, 55, 56, 57, 58, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, 75, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 95, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 113, 114, 115, 116, 117, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137 ]
45.588235
[]
0
false
100
138
16
100
45
def html_embed( clip, filetype=None, maxduration=60, rd_kwargs=None, center=True, **html_kwargs ): if rd_kwargs is None: # pragma: no cover rd_kwargs = {} if "Clip" in str(clip.__class__): TEMP_PREFIX = "__temp__" if isinstance(clip, ImageClip): filename = TEMP_PREFIX + ".png" kwargs = {"filename": filename, "with_mask": True} argnames = inspect.getfullargspec(clip.save_frame).args kwargs.update( {key: value for key, value in rd_kwargs.items() if key in argnames} ) clip.save_frame(**kwargs) elif isinstance(clip, VideoClip): filename = TEMP_PREFIX + ".mp4" kwargs = {"filename": filename, "preset": "ultrafast"} kwargs.update(rd_kwargs) clip.write_videofile(**kwargs) elif isinstance(clip, AudioClip): filename = TEMP_PREFIX + ".mp3" kwargs = {"filename": filename} kwargs.update(rd_kwargs) clip.write_audiofile(**kwargs) else: raise ValueError("Unknown class for the clip. Cannot embed and preview.") return html_embed( filename, maxduration=maxduration, rd_kwargs=rd_kwargs, center=center, **html_kwargs, ) filename = clip options = " ".join(["%s='%s'" % (str(k), str(v)) for k, v in html_kwargs.items()]) name, ext = os.path.splitext(filename) ext = ext[1:] if filetype is None: ext = filename.split(".")[-1].lower() if ext == "gif": filetype = "image" elif ext in extensions_dict: filetype = extensions_dict[ext]["type"] else: raise ValueError( "No file type is known for the provided file. Please provide " "argument `filetype` (one of 'image', 'video', 'sound') to the " "ipython display function." ) if filetype == "video": # The next lines set the HTML5-cvompatible extension and check that the # extension is HTML5-valid exts_htmltype = {"mp4": "mp4", "webm": "webm", "ogv": "ogg"} allowed_exts = " ".join(exts_htmltype.keys()) try: ext = exts_htmltype[ext] except Exception: raise ValueError( "This video extension cannot be displayed in the " "IPython Notebook. Allowed extensions: " + allowed_exts ) if filetype in ["audio", "video"]: duration = ffmpeg_parse_infos(filename, decode_file=True)["duration"] if duration > maxduration: raise ValueError( ( "The duration of video %s (%.1f) exceeds the 'maxduration'" " attribute. You can increase 'maxduration', by passing" " 'maxduration' parameter to ipython_display function." " But note that embedding large videos may take all the memory" " away!" ) % (filename, duration) ) with open(filename, "rb") as file: data = b64encode(file.read()).decode("utf-8") template = templates[filetype] result = template % {"data": data, "options": options, "ext": ext} if center: result = r"<div align=middle>%s</div>" % result return result
28,534
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/html_tools.py
ipython_display
( clip, filetype=None, maxduration=60, t=None, fps=None, rd_kwargs=None, center=True, **html_kwargs, )
return HTML2( html_embed( clip, filetype=filetype, maxduration=maxduration, center=center, rd_kwargs=rd_kwargs, **html_kwargs, ) )
Displays clip content in an IPython Notebook. Remarks: If your browser doesn't support HTML5, this should warn you. If nothing is displayed, maybe your file or filename is wrong. Important: The media will be physically embedded in the notebook. Parameters ---------- clip : moviepy.Clip.Clip Either the name of a file, or a clip to preview. The clip will actually be written to a file and embedded as if a filename was provided. filetype : str, optional One of ``"video"``, ``"image"`` or ``"audio"``. If None is given, it is determined based on the extension of ``filename``, but this can bug. maxduration : float, optional An error will be raised if the clip's duration is more than the indicated value (in seconds), to avoid spoiling the browser's cache and the RAM. t : float, optional If not None, only the frame at time t will be displayed in the notebook, instead of a video of the clip. fps : int, optional Enables to specify an fps, as required for clips whose fps is unknown. rd_kwargs : dict, optional Keyword arguments for the rendering, like ``dict(fps=15, bitrate="50k")``. Allow you to give some options to the render process. You can, for example, disable the logger bar passing ``dict(logger=None)``. center : bool, optional If true (default), the content will be wrapped in a ``<div align=middle>`` HTML container, so the content will be displayed at the center. kwargs Allow you to give some options, like ``width=260``, etc. When editing looping gifs, a good choice is ``loop=1, autoplay=1``. Examples -------- >>> from moviepy.editor import * >>> # later ... >>> clip.ipython_display(width=360) >>> clip.audio.ipython_display() >>> clip.write_gif("test.gif") >>> ipython_display('test.gif') >>> clip.save_frame("first_frame.jpeg") >>> ipython_display("first_frame.jpeg")
Displays clip content in an IPython Notebook.
194
281
def ipython_display( clip, filetype=None, maxduration=60, t=None, fps=None, rd_kwargs=None, center=True, **html_kwargs, ): """Displays clip content in an IPython Notebook. Remarks: If your browser doesn't support HTML5, this should warn you. If nothing is displayed, maybe your file or filename is wrong. Important: The media will be physically embedded in the notebook. Parameters ---------- clip : moviepy.Clip.Clip Either the name of a file, or a clip to preview. The clip will actually be written to a file and embedded as if a filename was provided. filetype : str, optional One of ``"video"``, ``"image"`` or ``"audio"``. If None is given, it is determined based on the extension of ``filename``, but this can bug. maxduration : float, optional An error will be raised if the clip's duration is more than the indicated value (in seconds), to avoid spoiling the browser's cache and the RAM. t : float, optional If not None, only the frame at time t will be displayed in the notebook, instead of a video of the clip. fps : int, optional Enables to specify an fps, as required for clips whose fps is unknown. rd_kwargs : dict, optional Keyword arguments for the rendering, like ``dict(fps=15, bitrate="50k")``. Allow you to give some options to the render process. You can, for example, disable the logger bar passing ``dict(logger=None)``. center : bool, optional If true (default), the content will be wrapped in a ``<div align=middle>`` HTML container, so the content will be displayed at the center. kwargs Allow you to give some options, like ``width=260``, etc. When editing looping gifs, a good choice is ``loop=1, autoplay=1``. Examples -------- >>> from moviepy.editor import * >>> # later ... >>> clip.ipython_display(width=360) >>> clip.audio.ipython_display() >>> clip.write_gif("test.gif") >>> ipython_display('test.gif') >>> clip.save_frame("first_frame.jpeg") >>> ipython_display("first_frame.jpeg") """ if not ipython_available: raise ImportError("Only works inside an IPython Notebook") if rd_kwargs is None: rd_kwargs = {} if fps is not None: rd_kwargs["fps"] = fps if t is not None: clip = clip.to_ImageClip(t) return HTML2( html_embed( clip, filetype=filetype, maxduration=maxduration, center=center, rd_kwargs=rd_kwargs, **html_kwargs, ) )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/html_tools.py#L194-L281
46
[ 0, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87 ]
27.272727
[]
0
false
100
88
5
100
55
def ipython_display( clip, filetype=None, maxduration=60, t=None, fps=None, rd_kwargs=None, center=True, **html_kwargs, ): if not ipython_available: raise ImportError("Only works inside an IPython Notebook") if rd_kwargs is None: rd_kwargs = {} if fps is not None: rd_kwargs["fps"] = fps if t is not None: clip = clip.to_ImageClip(t) return HTML2( html_embed( clip, filetype=filetype, maxduration=maxduration, center=center, rd_kwargs=rd_kwargs, **html_kwargs, ) )
28,535
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
ffmpeg_write_video
( clip, filename, fps, codec="libx264", bitrate=None, preset="medium", with_mask=False, write_logfile=False, audiofile=None, threads=None, ffmpeg_params=None, logger="bar", pixel_format=None, )
Write the clip to a videofile. See VideoClip.write_videofile for details on the parameters.
Write the clip to a videofile. See VideoClip.write_videofile for details on the parameters.
219
272
def ffmpeg_write_video( clip, filename, fps, codec="libx264", bitrate=None, preset="medium", with_mask=False, write_logfile=False, audiofile=None, threads=None, ffmpeg_params=None, logger="bar", pixel_format=None, ): """Write the clip to a videofile. See VideoClip.write_videofile for details on the parameters. """ logger = proglog.default_bar_logger(logger) if write_logfile: logfile = open(filename + ".log", "w+") else: logfile = None logger(message="Moviepy - Writing video %s\n" % filename) if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" with FFMPEG_VideoWriter( filename, clip.size, fps, codec=codec, preset=preset, bitrate=bitrate, logfile=logfile, audiofile=audiofile, threads=threads, ffmpeg_params=ffmpeg_params, pixel_format=pixel_format, ) as writer: for t, frame in clip.iter_frames( logger=logger, with_times=True, fps=fps, dtype="uint8" ): if with_mask: mask = 255 * clip.mask.get_frame(t) if mask.dtype != "uint8": mask = mask.astype("uint8") frame = np.dstack([frame, mask]) writer.write_frame(frame) if write_logfile: logfile.close() logger(message="Moviepy - Done !")
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L219-L272
46
[ 0, 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 ]
70.37037
[]
0
false
93.548387
54
8
100
2
def ffmpeg_write_video( clip, filename, fps, codec="libx264", bitrate=None, preset="medium", with_mask=False, write_logfile=False, audiofile=None, threads=None, ffmpeg_params=None, logger="bar", pixel_format=None, ): logger = proglog.default_bar_logger(logger) if write_logfile: logfile = open(filename + ".log", "w+") else: logfile = None logger(message="Moviepy - Writing video %s\n" % filename) if not pixel_format: pixel_format = "rgba" if with_mask else "rgb24" with FFMPEG_VideoWriter( filename, clip.size, fps, codec=codec, preset=preset, bitrate=bitrate, logfile=logfile, audiofile=audiofile, threads=threads, ffmpeg_params=ffmpeg_params, pixel_format=pixel_format, ) as writer: for t, frame in clip.iter_frames( logger=logger, with_times=True, fps=fps, dtype="uint8" ): if with_mask: mask = 255 * clip.mask.get_frame(t) if mask.dtype != "uint8": mask = mask.astype("uint8") frame = np.dstack([frame, mask]) writer.write_frame(frame) if write_logfile: logfile.close() logger(message="Moviepy - Done !")
28,536
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
ffmpeg_write_image
(filename, image, logfile=False, pixel_format=None)
Writes an image (HxWx3 or HxWx4 numpy array) to a file, using ffmpeg. Parameters ---------- filename : str Path to the output file. image : np.ndarray Numpy array with the image data. logfile : bool, optional Writes the ffmpeg output inside a logging file (``True``) or not (``False``). pixel_format : str, optional Pixel format for ffmpeg. If not defined, it will be discovered checking if the image data contains an alpha channel (``"rgba"``) or not (``"rgb24"``).
Writes an image (HxWx3 or HxWx4 numpy array) to a file, using ffmpeg.
275
335
def ffmpeg_write_image(filename, image, logfile=False, pixel_format=None): """Writes an image (HxWx3 or HxWx4 numpy array) to a file, using ffmpeg. Parameters ---------- filename : str Path to the output file. image : np.ndarray Numpy array with the image data. logfile : bool, optional Writes the ffmpeg output inside a logging file (``True``) or not (``False``). pixel_format : str, optional Pixel format for ffmpeg. If not defined, it will be discovered checking if the image data contains an alpha channel (``"rgba"``) or not (``"rgb24"``). """ if image.dtype != "uint8": image = image.astype("uint8") if not pixel_format: pixel_format = "rgba" if (image.shape[2] == 4) else "rgb24" cmd = [ FFMPEG_BINARY, "-y", "-s", "%dx%d" % (image.shape[:2][::-1]), "-f", "rawvideo", "-pix_fmt", pixel_format, "-i", "-", filename, ] if logfile: log_file = open(filename + ".log", "w+") else: log_file = sp.PIPE popen_params = cross_platform_popen_params( {"stdout": sp.DEVNULL, "stderr": log_file, "stdin": sp.PIPE} ) proc = sp.Popen(cmd, **popen_params) out, err = proc.communicate(image.tobytes()) if proc.returncode: error = ( f"{err}\n\nMoviePy error: FFMPEG encountered the following error while " f"writing file {filename} with command {cmd}:\n\n {err.decode()}" ) raise IOError(error) del proc
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L275-L335
46
[ 0, 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 ]
100
[]
0
true
93.548387
61
5
100
19
def ffmpeg_write_image(filename, image, logfile=False, pixel_format=None): if image.dtype != "uint8": image = image.astype("uint8") if not pixel_format: pixel_format = "rgba" if (image.shape[2] == 4) else "rgb24" cmd = [ FFMPEG_BINARY, "-y", "-s", "%dx%d" % (image.shape[:2][::-1]), "-f", "rawvideo", "-pix_fmt", pixel_format, "-i", "-", filename, ] if logfile: log_file = open(filename + ".log", "w+") else: log_file = sp.PIPE popen_params = cross_platform_popen_params( {"stdout": sp.DEVNULL, "stderr": log_file, "stdin": sp.PIPE} ) proc = sp.Popen(cmd, **popen_params) out, err = proc.communicate(image.tobytes()) if proc.returncode: error = ( f"{err}\n\nMoviePy error: FFMPEG encountered the following error while " f"writing file {filename} with command {cmd}:\n\n {err.decode()}" ) raise IOError(error) del proc
28,537
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
FFMPEG_VideoWriter.__init__
( self, filename, size, fps, codec="libx264", audiofile=None, preset="medium", bitrate=None, with_mask=False, logfile=None, threads=None, ffmpeg_params=None, pixel_format=None, )
77
140
def __init__( self, filename, size, fps, codec="libx264", audiofile=None, preset="medium", bitrate=None, with_mask=False, logfile=None, threads=None, ffmpeg_params=None, pixel_format=None, ): if logfile is None: logfile = sp.PIPE self.logfile = logfile self.filename = filename self.codec = codec self.ext = self.filename.split(".")[-1] if not pixel_format: # pragma: no cover pixel_format = "rgba" if with_mask else "rgb24" # order is important cmd = [ FFMPEG_BINARY, "-y", "-loglevel", "error" if logfile == sp.PIPE else "info", "-f", "rawvideo", "-vcodec", "rawvideo", "-s", "%dx%d" % (size[0], size[1]), "-pix_fmt", pixel_format, "-r", "%.02f" % fps, "-an", "-i", "-", ] if audiofile is not None: cmd.extend(["-i", audiofile, "-acodec", "copy"]) cmd.extend(["-vcodec", codec, "-preset", preset]) if ffmpeg_params is not None: cmd.extend(ffmpeg_params) if bitrate is not None: cmd.extend(["-b", bitrate]) if threads is not None: cmd.extend(["-threads", str(threads)]) if (codec == "libx264") and (size[0] % 2 == 0) and (size[1] % 2 == 0): cmd.extend(["-pix_fmt", "yuv420p"]) cmd.extend([filename]) popen_params = cross_platform_popen_params( {"stdout": sp.DEVNULL, "stderr": logfile, "stdin": sp.PIPE} ) self.proc = sp.Popen(cmd, **popen_params)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L77-L140
46
[ 0, 15, 16, 17, 18, 19, 20, 24, 25, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 62, 63 ]
43.548387
[]
0
false
93.548387
64
10
100
0
def __init__( self, filename, size, fps, codec="libx264", audiofile=None, preset="medium", bitrate=None, with_mask=False, logfile=None, threads=None, ffmpeg_params=None, pixel_format=None, ): if logfile is None: logfile = sp.PIPE self.logfile = logfile self.filename = filename self.codec = codec self.ext = self.filename.split(".")[-1] if not pixel_format: # pragma: no cover pixel_format = "rgba" if with_mask else "rgb24" # order is important cmd = [ FFMPEG_BINARY, "-y", "-loglevel", "error" if logfile == sp.PIPE else "info", "-f", "rawvideo", "-vcodec", "rawvideo", "-s", "%dx%d" % (size[0], size[1]), "-pix_fmt", pixel_format, "-r", "%.02f" % fps, "-an", "-i", "-", ] if audiofile is not None: cmd.extend(["-i", audiofile, "-acodec", "copy"]) cmd.extend(["-vcodec", codec, "-preset", preset]) if ffmpeg_params is not None: cmd.extend(ffmpeg_params) if bitrate is not None: cmd.extend(["-b", bitrate]) if threads is not None: cmd.extend(["-threads", str(threads)]) if (codec == "libx264") and (size[0] % 2 == 0) and (size[1] % 2 == 0): cmd.extend(["-pix_fmt", "yuv420p"]) cmd.extend([filename]) popen_params = cross_platform_popen_params( {"stdout": sp.DEVNULL, "stderr": logfile, "stdin": sp.PIPE} ) self.proc = sp.Popen(cmd, **popen_params)
28,538
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
FFMPEG_VideoWriter.write_frame
(self, img_array)
Writes one frame in the file.
Writes one frame in the file.
142
198
def write_frame(self, img_array): """Writes one frame in the file.""" try: self.proc.stdin.write(img_array.tobytes()) except IOError as err: _, ffmpeg_error = self.proc.communicate() if ffmpeg_error is not None: ffmpeg_error = ffmpeg_error.decode() else: # The error was redirected to a logfile with `write_logfile=True`, # so read the error from that file instead self.logfile.seek(0) ffmpeg_error = self.logfile.read() error = ( f"{err}\n\nMoviePy error: FFMPEG encountered the following error while " f"writing file {self.filename}:\n\n {ffmpeg_error}" ) if "Unknown encoder" in ffmpeg_error: error += ( "\n\nThe video export failed because FFMPEG didn't find the " f"specified codec for video encoding {self.codec}. " "Please install this codec or change the codec when calling " "write_videofile.\nFor instance:\n" " >>> clip.write_videofile('myvid.webm', codec='libvpx')" ) elif "incorrect codec parameters ?" in ffmpeg_error: error += ( "\n\nThe video export failed, possibly because the codec " f"specified for the video {self.codec} is not compatible with " f"the given extension {self.ext}.\n" "Please specify a valid 'codec' argument in write_videofile.\n" "This would be 'libx264' or 'mpeg4' for mp4, " "'libtheora' for ogv, 'libvpx for webm.\n" "Another possible reason is that the audio codec was not " "compatible with the video codec. For instance, the video " "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a" "video codec." ) elif "bitrate not specified" in ffmpeg_error: error += ( "\n\nThe video export failed, possibly because the bitrate " "specified was too high or too low for the video codec." ) elif "Invalid encoder type" in ffmpeg_error: error += ( "\n\nThe video export failed because the codec " "or file extension you provided is not suitable for video" ) raise IOError(error)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L142-L198
46
[ 0, 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, 55, 56 ]
52.631579
[ 28, 29, 42, 44, 49, 51 ]
10.526316
false
93.548387
57
7
89.473684
1
def write_frame(self, img_array): try: self.proc.stdin.write(img_array.tobytes()) except IOError as err: _, ffmpeg_error = self.proc.communicate() if ffmpeg_error is not None: ffmpeg_error = ffmpeg_error.decode() else: # The error was redirected to a logfile with `write_logfile=True`, # so read the error from that file instead self.logfile.seek(0) ffmpeg_error = self.logfile.read() error = ( f"{err}\n\nMoviePy error: FFMPEG encountered the following error while " f"writing file {self.filename}:\n\n {ffmpeg_error}" ) if "Unknown encoder" in ffmpeg_error: error += ( "\n\nThe video export failed because FFMPEG didn't find the " f"specified codec for video encoding {self.codec}. " "Please install this codec or change the codec when calling " "write_videofile.\nFor instance:\n" " >>> clip.write_videofile('myvid.webm', codec='libvpx')" ) elif "incorrect codec parameters ?" in ffmpeg_error: error += ( "\n\nThe video export failed, possibly because the codec " f"specified for the video {self.codec} is not compatible with " f"the given extension {self.ext}.\n" "Please specify a valid 'codec' argument in write_videofile.\n" "This would be 'libx264' or 'mpeg4' for mp4, " "'libtheora' for ogv, 'libvpx for webm.\n" "Another possible reason is that the audio codec was not " "compatible with the video codec. For instance, the video " "extensions 'ogv' and 'webm' only allow 'libvorbis' (default) as a" "video codec." ) elif "bitrate not specified" in ffmpeg_error: error += ( "\n\nThe video export failed, possibly because the bitrate " "specified was too high or too low for the video codec." ) elif "Invalid encoder type" in ffmpeg_error: error += ( "\n\nThe video export failed because the codec " "or file extension you provided is not suitable for video" ) raise IOError(error)
28,539
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
FFMPEG_VideoWriter.close
(self)
Closes the writer, terminating the subprocess if is still alive.
Closes the writer, terminating the subprocess if is still alive.
200
208
def close(self): """Closes the writer, terminating the subprocess if is still alive.""" if self.proc: self.proc.stdin.close() if self.proc.stderr is not None: self.proc.stderr.close() self.proc.wait() self.proc = None
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L200-L208
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]
100
[]
0
true
93.548387
9
3
100
1
def close(self): if self.proc: self.proc.stdin.close() if self.proc.stderr is not None: self.proc.stderr.close() self.proc.wait() self.proc = None
28,540
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
FFMPEG_VideoWriter.__enter__
(self)
return self
212
213
def __enter__(self): return self
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L212-L213
46
[ 0, 1 ]
100
[]
0
true
93.548387
2
1
100
0
def __enter__(self): return self
28,541
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_writer.py
FFMPEG_VideoWriter.__exit__
(self, exc_type, exc_value, traceback)
215
216
def __exit__(self, exc_type, exc_value, traceback): self.close()
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_writer.py#L215-L216
46
[ 0, 1 ]
100
[]
0
true
93.548387
2
1
100
0
def __exit__(self, exc_type, exc_value, traceback): self.close()
28,542
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_tools.py
ffmpeg_extract_subclip
( inputfile, start_time, end_time, outputfile=None, logger="bar" )
Makes a new video file playing video file between two times. Parameters ---------- inputfile : str Path to the file from which the subclip will be extracted. start_time : float Moment of the input clip that marks the start of the produced subclip. end_time : float Moment of the input clip that marks the end of the produced subclip. outputfile : str, optional Path to the output file. Defaults to ``<inputfile_name>SUB<start_time>_<end_time><ext>``.
Makes a new video file playing video file between two times.
12
56
def ffmpeg_extract_subclip( inputfile, start_time, end_time, outputfile=None, logger="bar" ): """Makes a new video file playing video file between two times. Parameters ---------- inputfile : str Path to the file from which the subclip will be extracted. start_time : float Moment of the input clip that marks the start of the produced subclip. end_time : float Moment of the input clip that marks the end of the produced subclip. outputfile : str, optional Path to the output file. Defaults to ``<inputfile_name>SUB<start_time>_<end_time><ext>``. """ if not outputfile: name, ext = os.path.splitext(inputfile) t1, t2 = [int(1000 * t) for t in [start_time, end_time]] outputfile = "%sSUB%d_%d%s" % (name, t1, t2, ext) cmd = [ FFMPEG_BINARY, "-y", "-ss", "%0.2f" % start_time, "-i", inputfile, "-t", "%0.2f" % (end_time - start_time), "-map", "0", "-vcodec", "copy", "-acodec", "copy", "-copyts", outputfile, ] subprocess_call(cmd, logger=logger)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_tools.py#L12-L56
46
[ 0, 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 ]
57.777778
[]
0
false
88.888889
45
3
100
17
def ffmpeg_extract_subclip( inputfile, start_time, end_time, outputfile=None, logger="bar" ): if not outputfile: name, ext = os.path.splitext(inputfile) t1, t2 = [int(1000 * t) for t in [start_time, end_time]] outputfile = "%sSUB%d_%d%s" % (name, t1, t2, ext) cmd = [ FFMPEG_BINARY, "-y", "-ss", "%0.2f" % start_time, "-i", inputfile, "-t", "%0.2f" % (end_time - start_time), "-map", "0", "-vcodec", "copy", "-acodec", "copy", "-copyts", outputfile, ] subprocess_call(cmd, logger=logger)
28,543
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_tools.py
ffmpeg_merge_video_audio
( videofile, audiofile, outputfile, video_codec="copy", audio_codec="copy", logger="bar", )
Merges video file and audio file into one movie file. Parameters ---------- videofile : str Path to the video file used in the merge. audiofile : str Path to the audio file used in the merge. outputfile : str Path to the output file. video_codec : str, optional Video codec used by FFmpeg in the merge. audio_codec : str, optional Audio codec used by FFmpeg in the merge.
Merges video file and audio file into one movie file.
60
102
def ffmpeg_merge_video_audio( videofile, audiofile, outputfile, video_codec="copy", audio_codec="copy", logger="bar", ): """Merges video file and audio file into one movie file. Parameters ---------- videofile : str Path to the video file used in the merge. audiofile : str Path to the audio file used in the merge. outputfile : str Path to the output file. video_codec : str, optional Video codec used by FFmpeg in the merge. audio_codec : str, optional Audio codec used by FFmpeg in the merge. """ cmd = [ FFMPEG_BINARY, "-y", "-i", audiofile, "-i", videofile, "-vcodec", video_codec, "-acodec", audio_codec, outputfile, ] subprocess_call(cmd, logger=logger)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_tools.py#L60-L102
46
[ 0 ]
2.325581
[ 28, 42 ]
4.651163
false
88.888889
43
1
95.348837
19
def ffmpeg_merge_video_audio( videofile, audiofile, outputfile, video_codec="copy", audio_codec="copy", logger="bar", ): cmd = [ FFMPEG_BINARY, "-y", "-i", audiofile, "-i", videofile, "-vcodec", video_codec, "-acodec", audio_codec, outputfile, ] subprocess_call(cmd, logger=logger)
28,544
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_tools.py
ffmpeg_extract_audio
(inputfile, outputfile, bitrate=3000, fps=44100, logger="bar")
Extract the sound from a video file and save it in ``outputfile``. Parameters ---------- inputfile : str The path to the file from which the audio will be extracted. outputfile : str The path to the file to which the audio will be stored. bitrate : int, optional Bitrate for the new audio file. fps : int, optional Frame rate for the new audio file.
Extract the sound from a video file and save it in ``outputfile``.
106
135
def ffmpeg_extract_audio(inputfile, outputfile, bitrate=3000, fps=44100, logger="bar"): """Extract the sound from a video file and save it in ``outputfile``. Parameters ---------- inputfile : str The path to the file from which the audio will be extracted. outputfile : str The path to the file to which the audio will be stored. bitrate : int, optional Bitrate for the new audio file. fps : int, optional Frame rate for the new audio file. """ cmd = [ FFMPEG_BINARY, "-y", "-i", inputfile, "-ab", "%dk" % bitrate, "-ar", "%d" % fps, outputfile, ] subprocess_call(cmd, logger=logger)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_tools.py#L106-L135
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
60
[ 18, 29 ]
6.666667
false
88.888889
30
1
93.333333
16
def ffmpeg_extract_audio(inputfile, outputfile, bitrate=3000, fps=44100, logger="bar"): cmd = [ FFMPEG_BINARY, "-y", "-i", inputfile, "-ab", "%dk" % bitrate, "-ar", "%d" % fps, outputfile, ] subprocess_call(cmd, logger=logger)
28,545
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_tools.py
ffmpeg_resize
(inputfile, outputfile, size, logger="bar")
Resizes a file to new size and write the result in another. Parameters ---------- inputfile : str Path to the file to be resized. outputfile : str Path to the output file. size : list or tuple New size in format ``[width, height]`` for the output file.
Resizes a file to new size and write the result in another.
139
163
def ffmpeg_resize(inputfile, outputfile, size, logger="bar"): """Resizes a file to new size and write the result in another. Parameters ---------- inputfile : str Path to the file to be resized. outputfile : str Path to the output file. size : list or tuple New size in format ``[width, height]`` for the output file. """ cmd = [ FFMPEG_BINARY, "-i", inputfile, "-vf", "scale=%d:%d" % (size[0], size[1]), outputfile, ] subprocess_call(cmd, logger=logger)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_tools.py#L139-L163
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
100
[]
0
true
88.888889
25
1
100
13
def ffmpeg_resize(inputfile, outputfile, size, logger="bar"): cmd = [ FFMPEG_BINARY, "-i", inputfile, "-vf", "scale=%d:%d" % (size[0], size[1]), outputfile, ] subprocess_call(cmd, logger=logger)
28,546
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/ffmpeg_tools.py
ffmpeg_stabilize_video
( inputfile, outputfile=None, output_dir="", overwrite_file=True, logger="bar" )
Stabilizes ``filename`` and write the result to ``output``. Parameters ---------- inputfile : str The name of the shaky video. outputfile : str, optional The name of new stabilized video. Defaults to appending '_stabilized' to the input file name. output_dir : str, optional The directory to place the output video in. Defaults to the current working directory. overwrite_file : bool, optional If ``outputfile`` already exists in ``output_dir``, then overwrite ``outputfile`` Defaults to True.
Stabilizes ``filename`` and write the result to ``output``.
167
200
def ffmpeg_stabilize_video( inputfile, outputfile=None, output_dir="", overwrite_file=True, logger="bar" ): """ Stabilizes ``filename`` and write the result to ``output``. Parameters ---------- inputfile : str The name of the shaky video. outputfile : str, optional The name of new stabilized video. Defaults to appending '_stabilized' to the input file name. output_dir : str, optional The directory to place the output video in. Defaults to the current working directory. overwrite_file : bool, optional If ``outputfile`` already exists in ``output_dir``, then overwrite ``outputfile`` Defaults to True. """ if not outputfile: without_dir = os.path.basename(inputfile) name, ext = os.path.splitext(without_dir) outputfile = f"{name}_stabilized{ext}" outputfile = os.path.join(output_dir, outputfile) cmd = [FFMPEG_BINARY, "-i", inputfile, "-vf", "deshake", outputfile] if overwrite_file: cmd.append("-y") subprocess_call(cmd, logger=logger)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/ffmpeg_tools.py#L167-L200
46
[ 0, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
35.294118
[]
0
false
88.888889
34
3
100
19
def ffmpeg_stabilize_video( inputfile, outputfile=None, output_dir="", overwrite_file=True, logger="bar" ): if not outputfile: without_dir = os.path.basename(inputfile) name, ext = os.path.splitext(without_dir) outputfile = f"{name}_stabilized{ext}" outputfile = os.path.join(output_dir, outputfile) cmd = [FFMPEG_BINARY, "-i", inputfile, "-vf", "deshake", outputfile] if overwrite_file: cmd.append("-y") subprocess_call(cmd, logger=logger)
28,547
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/bindings.py
mplfig_to_npimage
(fig)
return image.reshape(h, w, 3)
Converts a matplotlib figure to a RGB frame after updating the canvas.
Converts a matplotlib figure to a RGB frame after updating the canvas.
8
23
def mplfig_to_npimage(fig): """Converts a matplotlib figure to a RGB frame after updating the canvas.""" # only the Agg backend now supports the tostring_rgb function from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) canvas.draw() # update/draw the elements # get the width and the height to resize the matrix l, b, w, h = canvas.figure.bbox.bounds w, h = int(w), int(h) # exports the canvas to a string buffer and then to a numpy nd.array buf = canvas.tostring_rgb() image = np.frombuffer(buf, dtype=np.uint8) return image.reshape(h, w, 3)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/bindings.py#L8-L23
46
[ 0, 1, 2 ]
18.75
[ 3, 5, 6, 9, 10, 13, 14, 15 ]
50
false
20
16
1
50
1
def mplfig_to_npimage(fig): # only the Agg backend now supports the tostring_rgb function from matplotlib.backends.backend_agg import FigureCanvasAgg canvas = FigureCanvasAgg(fig) canvas.draw() # update/draw the elements # get the width and the height to resize the matrix l, b, w, h = canvas.figure.bbox.bounds w, h = int(w), int(h) # exports the canvas to a string buffer and then to a numpy nd.array buf = canvas.tostring_rgb() image = np.frombuffer(buf, dtype=np.uint8) return image.reshape(h, w, 3)
28,548
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/io/downloader.py
download_webfile
(url, filename, overwrite=False)
Small utility to download the file at ``url`` under name ``filename``. Parameters ---------- url : str If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl. Requires youtube-dl (pip install youtube-dl). filename : str Path to the new downloaded file location. overwrite : bool, optional If the filename already exists and overwrite=False, nothing will happen. Use it to force destination file overwriting. Examples -------- >>> from moviepy.io.downloader import download_website >>> >>> download_website( ... "http://localhost:8000/media/chaplin.mp4", ... "media/chaplin-copy.mp4", ... ) >>>
Small utility to download the file at ``url`` under name ``filename``.
10
56
def download_webfile(url, filename, overwrite=False): """Small utility to download the file at ``url`` under name ``filename``. Parameters ---------- url : str If url is a youtube video ID like z410eauCnH it will download the video using youtube-dl. Requires youtube-dl (pip install youtube-dl). filename : str Path to the new downloaded file location. overwrite : bool, optional If the filename already exists and overwrite=False, nothing will happen. Use it to force destination file overwriting. Examples -------- >>> from moviepy.io.downloader import download_website >>> >>> download_website( ... "http://localhost:8000/media/chaplin.mp4", ... "media/chaplin-copy.mp4", ... ) >>> """ if os.path.exists(filename) and not overwrite: # pragma: no cover return if "." in url: with urllib.request.urlopen(url) as req, open(filename, "wb") as f: shutil.copyfileobj(req, f, 128) else: try: subprocess_call(["youtube-dl", url, "-o", filename]) except OSError as e: raise OSError( ( "Error running youtube-dl.\n%sA possible reason is that" " youtube-dl is not installed on your computer. Install it " " with 'pip install youtube_dl'." ) % ((e.message + "\n" if hasattr(e, "message") else "")) )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/io/downloader.py#L10-L56
46
[ 0, 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 ]
104.444444
[]
0
true
100
47
6
100
26
def download_webfile(url, filename, overwrite=False): if os.path.exists(filename) and not overwrite: # pragma: no cover return if "." in url: with urllib.request.urlopen(url) as req, open(filename, "wb") as f: shutil.copyfileobj(req, f, 128) else: try: subprocess_call(["youtube-dl", url, "-o", filename]) except OSError as e: raise OSError( ( "Error running youtube-dl.\n%sA possible reason is that" " youtube-dl is not installed on your computer. Install it " " with 'pip install youtube_dl'." ) % ((e.message + "\n" if hasattr(e, "message") else "")) )
28,549
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/rotate.py
rotate
( clip, angle, unit="deg", resample="bicubic", expand=True, center=None, translate=None, bg_color=None, )
return clip.transform(filter, apply_to=["mask"])
Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``, and ``bg_color`` are not ``None``, the package ``pillow`` must be installed, and there will be black borders. You can make them transparent with: >>> new_clip = clip.add_mask().rotate(72) Parameters ---------- clip : VideoClip A video clip. angle : float Either a value or a function angle(t) representing the angle of rotation. unit : str, optional Unit of parameter `angle` (either "deg" for degrees or "rad" for radians). resample : str, optional An optional resampling filter. One of "nearest", "bilinear", or "bicubic". expand : bool, optional If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. translate : tuple, optional An optional post-rotate translation (a 2-tuple). center : tuple, optional Optional center of rotation (a 2-tuple). Origin is the upper left corner. bg_color : tuple, optional An optional color for area outside the rotated image. Only has effect if ``expand`` is true.
Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``, and ``bg_color`` are not ``None``, the package ``pillow`` must be installed, and there will be black borders. You can make them transparent with:
33
166
def rotate( clip, angle, unit="deg", resample="bicubic", expand=True, center=None, translate=None, bg_color=None, ): """ Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``, and ``bg_color`` are not ``None``, the package ``pillow`` must be installed, and there will be black borders. You can make them transparent with: >>> new_clip = clip.add_mask().rotate(72) Parameters ---------- clip : VideoClip A video clip. angle : float Either a value or a function angle(t) representing the angle of rotation. unit : str, optional Unit of parameter `angle` (either "deg" for degrees or "rad" for radians). resample : str, optional An optional resampling filter. One of "nearest", "bilinear", or "bicubic". expand : bool, optional If true, expands the output image to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. translate : tuple, optional An optional post-rotate translation (a 2-tuple). center : tuple, optional Optional center of rotation (a 2-tuple). Origin is the upper left corner. bg_color : tuple, optional An optional color for area outside the rotated image. Only has effect if ``expand`` is true. """ if Image: try: resample = { "bilinear": Image.BILINEAR, "nearest": Image.NEAREST, "bicubic": Image.BICUBIC, }[resample] except KeyError: raise ValueError( "'resample' argument must be either 'bilinear', 'nearest' or 'bicubic'" ) if hasattr(angle, "__call__"): get_angle = angle else: get_angle = lambda t: angle def filter(get_frame, t): angle = get_angle(t) im = get_frame(t) if unit == "rad": angle = math.degrees(angle) angle %= 360 if not center and not translate and not bg_color: if (angle == 0) and expand: return im if (angle == 90) and expand: transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2] return np.transpose(im, axes=transpose)[::-1] elif (angle == 270) and expand: transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2] return np.transpose(im, axes=transpose)[:, ::-1] elif (angle == 180) and expand: return im[::-1, ::-1] if not Image: raise ValueError( 'Without "Pillow" installed, only angles that are a multiple of 90' " without centering, translation and background color transformations" ' are supported, please install "Pillow" with `pip install pillow`' ) # build PIL.rotate kwargs kwargs, _locals = ({}, locals()) for PIL_rotate_kw_name, ( kw_name, supported, min_version, ) in PIL_rotate_kwargs_supported.items(): # get the value passed to rotate FX from `locals()` dictionary kw_value = _locals[kw_name] if supported: # if argument supported by PIL version kwargs[PIL_rotate_kw_name] = kw_value else: if kw_value is not None: # if not default value warnings.warn( f"rotate '{kw_name}' argument is not supported" " by your Pillow version and is being ignored. Minimum" " Pillow version required:" f" v{'.'.join(str(n) for n in min_version)}", UserWarning, ) # PIL expects uint8 type data. However a mask image has values in the # range [0, 1] and is of float type. To handle this we scale it up by # a factor 'a' for use with PIL and then back again by 'a' afterwards. if im.dtype == "float64": # this is a mask image a = 255.0 else: a = 1 # call PIL.rotate return ( np.array( Image.fromarray(np.array(a * im).astype(np.uint8)).rotate( angle, expand=expand, resample=resample, **kwargs ) ) / a ) return clip.transform(filter, apply_to=["mask"])
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/rotate.py#L33-L166
46
[ 0, 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 ]
65.671642
[]
0
false
100
134
22
100
36
def rotate( clip, angle, unit="deg", resample="bicubic", expand=True, center=None, translate=None, bg_color=None, ): if Image: try: resample = { "bilinear": Image.BILINEAR, "nearest": Image.NEAREST, "bicubic": Image.BICUBIC, }[resample] except KeyError: raise ValueError( "'resample' argument must be either 'bilinear', 'nearest' or 'bicubic'" ) if hasattr(angle, "__call__"): get_angle = angle else: get_angle = lambda t: angle def filter(get_frame, t): angle = get_angle(t) im = get_frame(t) if unit == "rad": angle = math.degrees(angle) angle %= 360 if not center and not translate and not bg_color: if (angle == 0) and expand: return im if (angle == 90) and expand: transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2] return np.transpose(im, axes=transpose)[::-1] elif (angle == 270) and expand: transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2] return np.transpose(im, axes=transpose)[:, ::-1] elif (angle == 180) and expand: return im[::-1, ::-1] if not Image: raise ValueError( 'Without "Pillow" installed, only angles that are a multiple of 90' " without centering, translation and background color transformations" ' are supported, please install "Pillow" with `pip install pillow`' ) # build PIL.rotate kwargs kwargs, _locals = ({}, locals()) for PIL_rotate_kw_name, ( kw_name, supported, min_version, ) in PIL_rotate_kwargs_supported.items(): # get the value passed to rotate FX from `locals()` dictionary kw_value = _locals[kw_name] if supported: # if argument supported by PIL version kwargs[PIL_rotate_kw_name] = kw_value else: if kw_value is not None: # if not default value warnings.warn( f"rotate '{kw_name}' argument is not supported" " by your Pillow version and is being ignored. Minimum" " Pillow version required:" f" v{'.'.join(str(n) for n in min_version)}", UserWarning, ) # PIL expects uint8 type data. However a mask image has values in the # range [0, 1] and is of float type. To handle this we scale it up by # a factor 'a' for use with PIL and then back again by 'a' afterwards. if im.dtype == "float64": # this is a mask image a = 255.0 else: a = 1 # call PIL.rotate return ( np.array( Image.fromarray(np.array(a * im).astype(np.uint8)).rotate( angle, expand=expand, resample=resample, **kwargs ) ) / a ) return clip.transform(filter, apply_to=["mask"])
28,550
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/painting.py
to_painting
(image, saturation=1.4, black=0.006)
return np.maximum(0, np.minimum(255, painting)).astype("uint8")
Transforms any photo into some kind of painting.
Transforms any photo into some kind of painting.
16
21
def to_painting(image, saturation=1.4, black=0.006): """Transforms any photo into some kind of painting.""" edges = sobel(image.mean(axis=2)) darkening = black * (255 * np.dstack(3 * [edges])) painting = saturation * image - darkening return np.maximum(0, np.minimum(255, painting)).astype("uint8")
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/painting.py#L16-L21
46
[ 0, 1 ]
33.333333
[ 2, 3, 4, 5 ]
66.666667
false
71.428571
6
1
33.333333
1
def to_painting(image, saturation=1.4, black=0.006): edges = sobel(image.mean(axis=2)) darkening = black * (255 * np.dstack(3 * [edges])) painting = saturation * image - darkening return np.maximum(0, np.minimum(255, painting)).astype("uint8")
28,551
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/painting.py
painting
(clip, saturation=1.4, black=0.006)
return clip.image_transform(lambda im: to_painting(im, saturation, black))
Transforms any photo into some kind of painting. Saturation tells at which point the colors of the result should be flashy. ``black`` gives the amount of black lines wanted. Requires Scikit-image or Scipy installed.
Transforms any photo into some kind of painting. Saturation tells at which point the colors of the result should be flashy. ``black`` gives the amount of black lines wanted. Requires Scikit-image or Scipy installed.
24
31
def painting(clip, saturation=1.4, black=0.006): """ Transforms any photo into some kind of painting. Saturation tells at which point the colors of the result should be flashy. ``black`` gives the amount of black lines wanted. Requires Scikit-image or Scipy installed. """ return clip.image_transform(lambda im: to_painting(im, saturation, black))
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/painting.py#L24-L31
46
[ 0, 1, 2, 3, 4, 5, 6 ]
87.5
[ 7 ]
12.5
false
71.428571
8
1
87.5
4
def painting(clip, saturation=1.4, black=0.006): return clip.image_transform(lambda im: to_painting(im, saturation, black))
28,552
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/loop.py
loop
(clip, n=None, duration=None)
return clip
Returns a clip that plays the current clip in an infinite loop. Ideal for clips coming from GIFs. Parameters ---------- n Number of times the clip should be played. If `None` the the clip will loop indefinitely (i.e. with no set duration). duration Total duration of the clip. Can be specified instead of n.
Returns a clip that plays the current clip in an infinite loop. Ideal for clips coming from GIFs.
5
28
def loop(clip, n=None, duration=None): """ Returns a clip that plays the current clip in an infinite loop. Ideal for clips coming from GIFs. Parameters ---------- n Number of times the clip should be played. If `None` the the clip will loop indefinitely (i.e. with no set duration). duration Total duration of the clip. Can be specified instead of n. """ previous_duration = clip.duration clip = clip.time_transform( lambda t: t % previous_duration, apply_to=["mask", "audio"] ) if n: duration = n * previous_duration if duration: clip = clip.with_duration(duration) return clip
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/loop.py#L5-L28
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
100
[]
0
true
100
24
3
100
12
def loop(clip, n=None, duration=None): previous_duration = clip.duration clip = clip.time_transform( lambda t: t % previous_duration, apply_to=["mask", "audio"] ) if n: duration = n * previous_duration if duration: clip = clip.with_duration(duration) return clip
28,553
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/margin.py
margin
( clip, margin_size=None, left=0, right=0, top=0, bottom=0, color=(0, 0, 0), opacity=1.0, )
Draws an external margin all around the frame. Parameters ---------- margin_size : int, optional If not ``None``, then the new clip has a margin size of size ``margin_size`` in pixels on the left, right, top, and bottom. left : int, optional If ``margin_size=None``, margin size for the new clip in left direction. right : int, optional If ``margin_size=None``, margin size for the new clip in right direction. top : int, optional If ``margin_size=None``, margin size for the new clip in top direction. bottom : int, optional If ``margin_size=None``, margin size for the new clip in bottom direction. color : tuple, optional Color of the margin. opacity : float, optional Opacity of the margin. Setting this value to 0 yields transparent margins.
Draws an external margin all around the frame.
8
76
def margin( clip, margin_size=None, left=0, right=0, top=0, bottom=0, color=(0, 0, 0), opacity=1.0, ): """ Draws an external margin all around the frame. Parameters ---------- margin_size : int, optional If not ``None``, then the new clip has a margin size of size ``margin_size`` in pixels on the left, right, top, and bottom. left : int, optional If ``margin_size=None``, margin size for the new clip in left direction. right : int, optional If ``margin_size=None``, margin size for the new clip in right direction. top : int, optional If ``margin_size=None``, margin size for the new clip in top direction. bottom : int, optional If ``margin_size=None``, margin size for the new clip in bottom direction. color : tuple, optional Color of the margin. opacity : float, optional Opacity of the margin. Setting this value to 0 yields transparent margins. """ if (opacity != 1.0) and (clip.mask is None) and not (clip.is_mask): clip = clip.add_mask() if margin_size is not None: left = right = top = bottom = margin_size def make_bg(w, h): new_w, new_h = w + left + right, h + top + bottom if clip.is_mask: shape = (new_h, new_w) bg = np.tile(opacity, (new_h, new_w)).astype(float).reshape(shape) else: shape = (new_h, new_w, 3) bg = np.tile(color, (new_h, new_w)).reshape(shape) return bg if isinstance(clip, ImageClip): im = make_bg(clip.w, clip.h) im[top : top + clip.h, left : left + clip.w] = clip.img return clip.image_transform(lambda pic: im) else: def filter(get_frame, t): pic = get_frame(t) h, w = pic.shape[:2] im = make_bg(w, h) im[top : top + h, left : left + w] = pic return im return clip.transform(filter)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/margin.py#L8-L76
46
[ 0, 37, 38, 40, 41, 42, 43, 44, 45, 46, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68 ]
43.478261
[ 39, 47, 48 ]
4.347826
false
89.285714
69
9
95.652174
26
def margin( clip, margin_size=None, left=0, right=0, top=0, bottom=0, color=(0, 0, 0), opacity=1.0, ): if (opacity != 1.0) and (clip.mask is None) and not (clip.is_mask): clip = clip.add_mask() if margin_size is not None: left = right = top = bottom = margin_size def make_bg(w, h): new_w, new_h = w + left + right, h + top + bottom if clip.is_mask: shape = (new_h, new_w) bg = np.tile(opacity, (new_h, new_w)).astype(float).reshape(shape) else: shape = (new_h, new_w, 3) bg = np.tile(color, (new_h, new_w)).reshape(shape) return bg if isinstance(clip, ImageClip): im = make_bg(clip.w, clip.h) im[top : top + clip.h, left : left + clip.w] = clip.img return clip.image_transform(lambda pic: im) else: def filter(get_frame, t): pic = get_frame(t) h, w = pic.shape[:2] im = make_bg(w, h) im[top : top + h, left : left + w] = pic return im return clip.transform(filter)
28,554
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/supersample.py
supersample
(clip, d, n_frames)
return clip.transform(filter)
Replaces each frame at time t by the mean of `n_frames` equally spaced frames taken in the interval [t-d, t+d]. This results in motion blur.
Replaces each frame at time t by the mean of `n_frames` equally spaced frames taken in the interval [t-d, t+d]. This results in motion blur.
4
16
def supersample(clip, d, n_frames): """Replaces each frame at time t by the mean of `n_frames` equally spaced frames taken in the interval [t-d, t+d]. This results in motion blur. """ def filter(get_frame, t): timings = np.linspace(t - d, t + d, n_frames) frame_average = np.mean( 1.0 * np.array([get_frame(t_) for t_ in timings], dtype="uint16"), axis=0 ) return frame_average.astype("uint8") return clip.transform(filter)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/supersample.py#L4-L16
46
[ 0, 1, 2, 3, 4 ]
38.461538
[ 5, 6, 7, 10, 12 ]
38.461538
false
28.571429
13
3
61.538462
2
def supersample(clip, d, n_frames): def filter(get_frame, t): timings = np.linspace(t - d, t + d, n_frames) frame_average = np.mean( 1.0 * np.array([get_frame(t_) for t_ in timings], dtype="uint16"), axis=0 ) return frame_average.astype("uint8") return clip.transform(filter)
28,555
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/time_mirror.py
time_mirror
(clip)
return clip.time_transform(lambda t: clip.duration - t - 1, keep_duration=True)
Returns a clip that plays the current clip backwards. The clip must have its ``duration`` attribute set. The same effect is applied to the clip's audio and mask if any.
Returns a clip that plays the current clip backwards. The clip must have its ``duration`` attribute set. The same effect is applied to the clip's audio and mask if any.
7
13
def time_mirror(clip): """ Returns a clip that plays the current clip backwards. The clip must have its ``duration`` attribute set. The same effect is applied to the clip's audio and mask if any. """ return clip.time_transform(lambda t: clip.duration - t - 1, keep_duration=True)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/time_mirror.py#L7-L13
46
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
100
7
1
100
3
def time_mirror(clip): return clip.time_transform(lambda t: clip.duration - t - 1, keep_duration=True)
28,556
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/invert_colors.py
invert_colors
(clip)
return clip.image_transform(lambda f: maxi - f)
Returns the color-inversed clip. The values of all pixels are replaced with (255-v) or (1-v) for masks Black becomes white, green becomes purple, etc.
Returns the color-inversed clip.
1
8
def invert_colors(clip): """Returns the color-inversed clip. The values of all pixels are replaced with (255-v) or (1-v) for masks Black becomes white, green becomes purple, etc. """ maxi = 1.0 if clip.is_mask else 255 return clip.image_transform(lambda f: maxi - f)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/invert_colors.py#L1-L8
46
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
100
8
1
100
4
def invert_colors(clip): maxi = 1.0 if clip.is_mask else 255 return clip.image_transform(lambda f: maxi - f)
28,557
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/blink.py
blink
(clip, duration_on, duration_off)
return new_clip
Makes the clip blink. At each blink it will be displayed ``duration_on`` seconds and disappear ``duration_off`` seconds. Will only work in composite clips.
Makes the clip blink. At each blink it will be displayed ``duration_on`` seconds and disappear ``duration_off`` seconds. Will only work in composite clips.
1
14
def blink(clip, duration_on, duration_off): """ Makes the clip blink. At each blink it will be displayed ``duration_on`` seconds and disappear ``duration_off`` seconds. Will only work in composite clips. """ new_clip = clip.copy() if new_clip.mask is None: new_clip = new_clip.with_mask() duration = duration_on + duration_off new_clip.mask = new_clip.mask.transform( lambda get_frame, t: get_frame(t) * ((t % duration) < duration_on) ) return new_clip
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/blink.py#L1-L14
46
[ 0, 1, 2, 3, 4, 5 ]
42.857143
[ 6, 7, 8, 9, 10, 13 ]
42.857143
false
14.285714
14
2
57.142857
3
def blink(clip, duration_on, duration_off): new_clip = clip.copy() if new_clip.mask is None: new_clip = new_clip.with_mask() duration = duration_on + duration_off new_clip.mask = new_clip.mask.transform( lambda get_frame, t: get_frame(t) * ((t % duration) < duration_on) ) return new_clip
28,558
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/mask_or.py
mask_or
(clip, other_clip)
Returns the logical 'or' (maximum pixel color values) between two masks. The result has the duration of the clip to which has been applied, if it has any. Parameters ---------- other_clip ImageClip or np.ndarray Clip used to mask the original clip. Examples -------- >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green >>> masked_clip = clip.fx(mask_or, mask) # yellow >>> masked_clip.get_frame(0) [[[255 255 0]]]
Returns the logical 'or' (maximum pixel color values) between two masks.
6
35
def mask_or(clip, other_clip): """Returns the logical 'or' (maximum pixel color values) between two masks. The result has the duration of the clip to which has been applied, if it has any. Parameters ---------- other_clip ImageClip or np.ndarray Clip used to mask the original clip. Examples -------- >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green >>> masked_clip = clip.fx(mask_or, mask) # yellow >>> masked_clip.get_frame(0) [[[255 255 0]]] """ # to ensure that 'or' of two ImageClips will be an ImageClip if isinstance(other_clip, ImageClip): other_clip = other_clip.img if isinstance(other_clip, np.ndarray): return clip.image_transform(lambda frame: np.maximum(frame, other_clip)) else: return clip.transform( lambda get_frame, t: np.maximum(get_frame(t), other_clip.get_frame(t)) )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/mask_or.py#L6-L35
46
[ 0, 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 ]
100
[]
0
true
100
30
3
100
18
def mask_or(clip, other_clip): # to ensure that 'or' of two ImageClips will be an ImageClip if isinstance(other_clip, ImageClip): other_clip = other_clip.img if isinstance(other_clip, np.ndarray): return clip.image_transform(lambda frame: np.maximum(frame, other_clip)) else: return clip.transform( lambda get_frame, t: np.maximum(get_frame(t), other_clip.get_frame(t)) )
28,559
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/crop.py
crop
( clip, x1=None, y1=None, x2=None, y2=None, width=None, height=None, x_center=None, y_center=None, )
return clip.image_transform( lambda frame: frame[int(y1) : int(y2), int(x1) : int(x2)], apply_to=["mask"] )
Returns a new clip in which just a rectangular subregion of the original clip is conserved. x1,y1 indicates the top left corner and x2,y2 is the lower right corner of the croped region. All coordinates are in pixels. Float numbers are accepted. To crop an arbitrary rectangle: >>> crop(clip, x1=50, y1=60, x2=460, y2=275) Only remove the part above y=30: >>> crop(clip, y1=30) Crop a rectangle that starts 10 pixels left and is 200px wide >>> crop(clip, x1=10, width=200) Crop a rectangle centered in x,y=(300,400), width=50, height=150 : >>> crop(clip, x_center=300 , y_center=400, width=50, height=150) Any combination of the above should work, like for this rectangle centered in x=300, with explicit y-boundaries: >>> crop(clip, x_center=300, width=400, y1=100, y2=600)
Returns a new clip in which just a rectangular subregion of the original clip is conserved. x1,y1 indicates the top left corner and x2,y2 is the lower right corner of the croped region. All coordinates are in pixels. Float numbers are accepted.
1
64
def crop( clip, x1=None, y1=None, x2=None, y2=None, width=None, height=None, x_center=None, y_center=None, ): """ Returns a new clip in which just a rectangular subregion of the original clip is conserved. x1,y1 indicates the top left corner and x2,y2 is the lower right corner of the croped region. All coordinates are in pixels. Float numbers are accepted. To crop an arbitrary rectangle: >>> crop(clip, x1=50, y1=60, x2=460, y2=275) Only remove the part above y=30: >>> crop(clip, y1=30) Crop a rectangle that starts 10 pixels left and is 200px wide >>> crop(clip, x1=10, width=200) Crop a rectangle centered in x,y=(300,400), width=50, height=150 : >>> crop(clip, x_center=300 , y_center=400, width=50, height=150) Any combination of the above should work, like for this rectangle centered in x=300, with explicit y-boundaries: >>> crop(clip, x_center=300, width=400, y1=100, y2=600) """ if width and x1 is not None: x2 = x1 + width elif width and x2 is not None: x1 = x2 - width if height and y1 is not None: y2 = y1 + height elif height and y2 is not None: y1 = y2 - height if x_center: x1, x2 = x_center - width / 2, x_center + width / 2 if y_center: y1, y2 = y_center - height / 2, y_center + height / 2 x1 = x1 or 0 y1 = y1 or 0 x2 = x2 or clip.size[0] y2 = y2 or clip.size[1] return clip.image_transform( lambda frame: frame[int(y1) : int(y2), int(x1) : int(x2)], apply_to=["mask"] )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/crop.py#L1-L64
46
[ 0, 39, 40, 41, 42, 44, 45, 47, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 ]
35.9375
[ 43, 46, 48 ]
4.6875
false
83.333333
64
15
95.3125
26
def crop( clip, x1=None, y1=None, x2=None, y2=None, width=None, height=None, x_center=None, y_center=None, ): if width and x1 is not None: x2 = x1 + width elif width and x2 is not None: x1 = x2 - width if height and y1 is not None: y2 = y1 + height elif height and y2 is not None: y1 = y2 - height if x_center: x1, x2 = x_center - width / 2, x_center + width / 2 if y_center: y1, y2 = y_center - height / 2, y_center + height / 2 x1 = x1 or 0 y1 = y1 or 0 x2 = x2 or clip.size[0] y2 = y2 or clip.size[1] return clip.image_transform( lambda frame: frame[int(y1) : int(y2), int(x1) : int(x2)], apply_to=["mask"] )
28,560
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/lum_contrast.py
lum_contrast
(clip, lum=0, contrast=0, contrast_threshold=127)
return clip.image_transform(image_filter)
Luminosity-contrast correction of a clip.
Luminosity-contrast correction of a clip.
1
11
def lum_contrast(clip, lum=0, contrast=0, contrast_threshold=127): """Luminosity-contrast correction of a clip.""" def image_filter(im): im = 1.0 * im # float conversion corrected = im + lum + contrast * (im - float(contrast_threshold)) corrected[corrected < 0] = 0 corrected[corrected > 255] = 255 return corrected.astype("uint8") return clip.image_transform(image_filter)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/lum_contrast.py#L1-L11
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
100
11
2
100
1
def lum_contrast(clip, lum=0, contrast=0, contrast_threshold=127): def image_filter(im): im = 1.0 * im # float conversion corrected = im + lum + contrast * (im - float(contrast_threshold)) corrected[corrected < 0] = 0 corrected[corrected > 255] = 255 return corrected.astype("uint8") return clip.image_transform(image_filter)
28,561
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/accel_decel.py
_f_accel_decel
(t, old_duration, new_duration, abruptness=1.0, soonness=1.0)
return old_duration * _f((t / new_duration) ** soonness)
1
13
def _f_accel_decel(t, old_duration, new_duration, abruptness=1.0, soonness=1.0): a = 1.0 + abruptness def _f(t): def f1(t): return (0.5) ** (1 - a) * (t**a) def f2(t): return 1 - f1(1 - t) return (t < 0.5) * f1(t) + (t >= 0.5) * f2(t) return old_duration * _f((t / new_duration) ** soonness)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/accel_decel.py#L1-L13
46
[ 0 ]
7.692308
[ 1, 3, 4, 5, 7, 8, 10, 12 ]
61.538462
false
13.333333
13
4
38.461538
0
def _f_accel_decel(t, old_duration, new_duration, abruptness=1.0, soonness=1.0): a = 1.0 + abruptness def _f(t): def f1(t): return (0.5) ** (1 - a) * (t**a) def f2(t): return 1 - f1(1 - t) return (t < 0.5) * f1(t) + (t >= 0.5) * f2(t) return old_duration * _f((t / new_duration) ** soonness)
28,562
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/accel_decel.py
accel_decel
(clip, new_duration=None, abruptness=1.0, soonness=1.0)
return clip.time_transform( lambda t: _f_accel_decel(t, clip.duration, new_duration, abruptness, soonness) ).with_duration(new_duration)
Accelerates and decelerates a clip, useful for GIF making. Parameters ---------- new_duration : float Duration for the new transformed clip. If None, will be that of the current clip. abruptness : float Slope shape in the acceleration-deceleration function. It will depend on the value of the parameter: * ``-1 < abruptness < 0``: speed up, down, up. * ``abruptness == 0``: no effect. * ``abruptness > 0``: speed down, up, down. soonness : float For positive abruptness, determines how soon the transformation occurs. Should be a positive number. Raises ------ ValueError When ``sooness`` argument is lower than 0. Examples -------- The following graphs show functions generated by different combinations of arguments, where the value of the slopes represents the speed of the videos generated, being the linear function (in red) a combination that does not produce any transformation. .. image:: /_static/accel_decel-fx-params.png :alt: acced_decel FX parameters combinations
Accelerates and decelerates a clip, useful for GIF making.
16
62
def accel_decel(clip, new_duration=None, abruptness=1.0, soonness=1.0): """Accelerates and decelerates a clip, useful for GIF making. Parameters ---------- new_duration : float Duration for the new transformed clip. If None, will be that of the current clip. abruptness : float Slope shape in the acceleration-deceleration function. It will depend on the value of the parameter: * ``-1 < abruptness < 0``: speed up, down, up. * ``abruptness == 0``: no effect. * ``abruptness > 0``: speed down, up, down. soonness : float For positive abruptness, determines how soon the transformation occurs. Should be a positive number. Raises ------ ValueError When ``sooness`` argument is lower than 0. Examples -------- The following graphs show functions generated by different combinations of arguments, where the value of the slopes represents the speed of the videos generated, being the linear function (in red) a combination that does not produce any transformation. .. image:: /_static/accel_decel-fx-params.png :alt: acced_decel FX parameters combinations """ if new_duration is None: new_duration = clip.duration if soonness < 0: raise ValueError("'sooness' should be a positive number") return clip.time_transform( lambda t: _f_accel_decel(t, clip.duration, new_duration, abruptness, soonness) ).with_duration(new_duration)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/accel_decel.py#L16-L62
46
[ 0, 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 ]
82.978723
[ 39, 40, 41, 42, 44 ]
10.638298
false
13.333333
47
3
89.361702
37
def accel_decel(clip, new_duration=None, abruptness=1.0, soonness=1.0): if new_duration is None: new_duration = clip.duration if soonness < 0: raise ValueError("'sooness' should be a positive number") return clip.time_transform( lambda t: _f_accel_decel(t, clip.duration, new_duration, abruptness, soonness) ).with_duration(new_duration)
28,563
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/scroll.py
scroll
( clip, w=None, h=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask" )
return clip.transform(filter, apply_to=apply_to)
Scrolls horizontally or vertically a clip, e.g. to make end credits Parameters ---------- w, h The width and height of the final clip. Default to clip.w and clip.h x_speed, y_speed x_start, y_start apply_to
Scrolls horizontally or vertically a clip, e.g. to make end credits
1
34
def scroll( clip, w=None, h=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask" ): """ Scrolls horizontally or vertically a clip, e.g. to make end credits Parameters ---------- w, h The width and height of the final clip. Default to clip.w and clip.h x_speed, y_speed x_start, y_start apply_to """ if h is None: h = clip.h if w is None: w = clip.w x_max = w - 1 y_max = h - 1 def filter(get_frame, t): x = int(max(0, min(x_max, x_start + round(x_speed * t)))) y = int(max(0, min(y_max, y_start + round(y_speed * t)))) return get_frame(t)[y : y + h, x : x + w] return clip.transform(filter, apply_to=apply_to)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/scroll.py#L1-L34
46
[ 0, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
44.117647
[ 23 ]
2.941176
false
91.666667
34
4
97.058824
14
def scroll( clip, w=None, h=None, x_speed=0, y_speed=0, x_start=0, y_start=0, apply_to="mask" ): if h is None: h = clip.h if w is None: w = clip.w x_max = w - 1 y_max = h - 1 def filter(get_frame, t): x = int(max(0, min(x_max, x_start + round(x_speed * t)))) y = int(max(0, min(y_max, y_start + round(y_speed * t)))) return get_frame(t)[y : y + h, x : x + w] return clip.transform(filter, apply_to=apply_to)
28,564
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/make_loopable.py
make_loopable
(clip, overlap_duration)
return CompositeVideoClip([clip, clip2]).subclip(overlap_duration, clip.duration)
Makes the clip fade in progressively at its own end, this way it can be looped indefinitely. Parameters ---------- overlap_duration : float Duration of the fade-in (in seconds).
Makes the clip fade in progressively at its own end, this way it can be looped indefinitely.
7
20
def make_loopable(clip, overlap_duration): """Makes the clip fade in progressively at its own end, this way it can be looped indefinitely. Parameters ---------- overlap_duration : float Duration of the fade-in (in seconds). """ clip2 = clip.fx(transfx.crossfadein, overlap_duration).with_start( clip.duration - overlap_duration ) return CompositeVideoClip([clip, clip2]).subclip(overlap_duration, clip.duration)
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/make_loopable.py#L7-L20
46
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]
100
[]
0
true
100
14
1
100
8
def make_loopable(clip, overlap_duration): clip2 = clip.fx(transfx.crossfadein, overlap_duration).with_start( clip.duration - overlap_duration ) return CompositeVideoClip([clip, clip2]).subclip(overlap_duration, clip.duration)
28,565
Zulko/moviepy
858bb81fba7e09f1f562283ed6d1394db883b6c7
moviepy/video/fx/mask_and.py
mask_and
(clip, other_clip)
Returns the logical 'and' (minimum pixel color values) between two masks. The result has the duration of the clip to which has been applied, if it has any. Parameters ---------- other_clip ImageClip or np.ndarray Clip used to mask the original clip. Examples -------- >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green >>> masked_clip = clip.fx(mask_and, mask) # black >>> masked_clip.get_frame(0) [[[0 0 0]]]
Returns the logical 'and' (minimum pixel color values) between two masks.
6
35
def mask_and(clip, other_clip): """Returns the logical 'and' (minimum pixel color values) between two masks. The result has the duration of the clip to which has been applied, if it has any. Parameters ---------- other_clip ImageClip or np.ndarray Clip used to mask the original clip. Examples -------- >>> clip = ColorClip(color=(255, 0, 0), size=(1, 1)) # red >>> mask = ColorClip(color=(0, 255, 0), size=(1, 1)) # green >>> masked_clip = clip.fx(mask_and, mask) # black >>> masked_clip.get_frame(0) [[[0 0 0]]] """ # to ensure that 'and' of two ImageClips will be an ImageClip if isinstance(other_clip, ImageClip): other_clip = other_clip.img if isinstance(other_clip, np.ndarray): return clip.image_transform(lambda frame: np.minimum(frame, other_clip)) else: return clip.transform( lambda get_frame, t: np.minimum(get_frame(t), other_clip.get_frame(t)) )
https://github.com/Zulko/moviepy/blob/858bb81fba7e09f1f562283ed6d1394db883b6c7/project46/moviepy/video/fx/mask_and.py#L6-L35
46
[ 0, 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 ]
100
[]
0
true
100
30
3
100
18
def mask_and(clip, other_clip): # to ensure that 'and' of two ImageClips will be an ImageClip if isinstance(other_clip, ImageClip): other_clip = other_clip.img if isinstance(other_clip, np.ndarray): return clip.image_transform(lambda frame: np.minimum(frame, other_clip)) else: return clip.transform( lambda get_frame, t: np.minimum(get_frame(t), other_clip.get_frame(t)) )
28,566