本文整理汇总了Python中moviepy.video.io.VideoFileClip.VideoFileClip类的典型用法代码示例。如果您正苦于以下问题:Python VideoFileClip类的具体用法?Python VideoFileClip怎么用?Python VideoFileClip使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VideoFileClip类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: cut_video
def cut_video(recording_path, datapack_dir):
# Read the start/end pattern
sr1, pattern_wav = wav.read('pattern.wav')
workingdir = tempfile.mkdtemp()
# Open the video file
clip = VideoFileClip(recording_path)
# Save its audio track temporarily on disk
clip.audio.write_audiofile(os.path.join(workingdir,"temp_audio.wav"))
# Read the audio samples, mix down to mono (if necessary), and delete the temporary audio track
sr2, recording_wav = wav.read(os.path.join(workingdir,"temp_audio.wav"))
if recording_wav.shape[1]>1:
recording_wav = numpy.mean(recording_wav,1)
shutil.rmtree(workingdir)
# Detect the start and end audio pattern
start, end = detect_start_end_times(pattern_wav, recording_wav, sr2, 4)
# Cut the video and write it into two separate video and audio files
clip.subclip(start+0.4, end).write_videofile(os.path.join(datapack_dir, 'video.mp4'), codec='libx264')
clip.subclip(start+0.4, end).audio.write_audiofile(os.path.join(datapack_dir,'audio.wav'))
示例2: summarize
def summarize(filepath, new_filename, hotclips):
"""
Inputs a filepath for a video and generates a new shorter video
in that same filepath.
"""
# Only open the file once!
video = VideoFileClip(filepath)
chunks = [video.subclip(start, end)
for (start, end) in hotclips]
final_clip = concatenate(chunks)
# txt_clip = ( TextClip("Generated by vSummarize",
# fontsize=20, color='white')
# .set_pos('bottom')
# .set_duration(5))
# final_clip = CompositeVideoClip([summarized_video, txt_clip])
# Use the to_videofile default codec, libx264
# libx264 is much better than mpeg4, and still writes .mp4
# Use the fps of the original video.
final_clip.to_videofile(new_filename,
fps=video.fps,
audio_codec='mp3')
示例3: test_toimageclip
def test_toimageclip():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.6)
clip = clip.to_ImageClip(t=0.1, duration=0.4)
location = os.path.join(TMP_DIR, "toimageclip.mp4")
clip.write_videofile(location, fps=24)
assert os.path.isfile(location)
close_all_clips(locals())
示例4: test_write_image_sequence
def test_write_image_sequence():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.5)
locations = clip.write_images_sequence(
os.path.join(TMP_DIR, "frame%02d.png"))
for location in locations:
assert os.path.isfile(location)
close_all_clips(locals())
示例5: VideoStim
class VideoStim(Stim, CollectionStimMixin):
''' A video. '''
def __init__(self, filename, onset=None):
self.clip = VideoFileClip(filename)
self.fps = self.clip.fps
self.width = self.clip.w
self.height = self.clip.h
self.n_frames = int(self.fps * self.clip.duration)
duration = self.clip.duration
super(VideoStim, self).__init__(filename, onset, duration)
def __iter__(self):
""" Frame iteration. """
for i, f in enumerate(self.clip.iter_frames()):
yield VideoFrameStim(self, i, data=f)
@property
def frames(self):
return [f for f in self.clip.iter_frames()]
def get_frame(self, index=None, onset=None):
if index is not None:
onset = float(index) / self.fps
else:
index = int(onset * self.fps)
return VideoFrameStim(self, index, data=self.clip.get_frame(onset))
示例6: _load_video
def _load_video(full_path, size = None, resize_mode = 'resize_and_crop', cut_edges=False, cut_edges_thresh=0):
"""
Lead a video into a numpy array
:param full_path: Full path to the video
:param size: A 2-tuple of width-height, indicating the desired size of the ouput
:param resize_mode: The mode with which to get the video to the desired size. Can be:
'squeeze', 'preserve_aspect', 'crop', 'scale_crop'. See resize_image in image_ops.py for more info.
:param cut_edges: True if you want to cut the dark edges from the video
:param cut_edges_thresh: If cut_edges, this is the threshold at which you'd like to cut them.
:return: A (n_frames, height, width, 3) numpy array
"""
try:
from moviepy.video.io.VideoFileClip import VideoFileClip
except ImportError:
raise ImportError("You need to install moviepy to read videos. In the virtualenv, go `pip install moviepy`")
assert os.path.exists(full_path)
video = VideoFileClip(full_path)
images = []
edge_crops = None
for frame in video.iter_frames():
if cut_edges:
if edge_crops is None:
edge_crops = get_dark_edge_slice(frame, cut_edges_thresh=cut_edges_thresh)
else:
frame = frame[edge_crops[0], edge_crops[1]]
if size is not None:
width, height = size
frame = resize_image(frame, width=width, height=height, mode=resize_mode)
images.append(frame)
return images
示例7: test_setopacity
def test_setopacity():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.6)
clip = clip.set_opacity(0.5)
clip = clip.on_color(size=(1000, 1000), color=(0, 0, 255), col_opacity=0.8)
location = os.path.join(TMP_DIR, "setopacity.mp4")
clip.write_videofile(location)
assert os.path.isfile(location)
close_all_clips(locals())
示例8: test_subfx
def test_subfx():
clip = VideoFileClip("media/big_buck_bunny_0_30.webm").subclip(0, 1)
transform = lambda c: speedx(c, 0.5)
new_clip = clip.subfx(transform, 0.5, 0.8)
location = os.path.join(TMP_DIR, "subfx.mp4")
new_clip.write_videofile(location)
assert os.path.isfile(location)
close_all_clips(locals())
示例9: test_failure_to_release_file
def test_failure_to_release_file():
""" This isn't really a test, because it is expected to fail.
It demonstrates that there *is* a problem with not releasing resources when running on
Windows.
The real issue was that, as of movepy 0.2.3.2, there was no way around it.
See test_resourcerelease.py to see how the close() methods provide a solution.
"""
# Get the name of a temporary file we can use.
local_video_filename = join(
TMP_DIR, "test_release_of_file_%s.mp4" % int(time.time()))
# Repeat this so we can see that the problems escalate:
for i in range(5):
# Create a random video file.
red = ColorClip((256, 200), color=(255, 0, 0))
green = ColorClip((256, 200), color=(0, 255, 0))
blue = ColorClip((256, 200), color=(0, 0, 255))
red.fps = green.fps = blue.fps = 30
video = clips_array([[red, green, blue]]).set_duration(1)
try:
video.write_videofile(local_video_filename)
# Open it up with VideoFileClip.
clip = VideoFileClip(local_video_filename)
# Normally a client would do processing here.
# All finished, so delete the clipS.
clip.close()
video.close()
del clip
del video
except IOError:
print(
"On Windows, this succeeds the first few times around the loop"
" but eventually fails.")
print("Need to shut down the process now. No more tests in"
"this file.")
return
try:
# Now remove the temporary file.
# This will fail on Windows if the file is still locked.
# In particular, this raises an exception with PermissionError.
# In there was no way to avoid it.
remove(local_video_filename)
print("You are not running Windows, because that worked.")
except OSError: # More specifically, PermissionError in Python 3.
print("Yes, on Windows this fails.")
示例10: test_check_codec
def test_check_codec():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm")
location = os.path.join(TMP_DIR, "not_a_video.mas")
try:
clip.write_videofile(location)
except ValueError as e:
assert "MoviePy couldn't find the codec associated with the filename." \
" Provide the 'codec' parameter in write_videofile." in str(e)
close_all_clips(locals())
示例11: test_loop
def test_loop():
#these do not work.. what am I doing wrong??
return
clip = VideoFileClip("media/big_buck_bunny_432_433.webm")
clip1 = clip.loop() #infinite looping
clip1.write_videofile(os.path.join(TMP_DIR, "loop1.webm"))
clip2 = clip.loop(duration=10) #loop for 10 seconds
clip2.write_videofile(os.path.join(TMP_DIR, "loop2.webm"))
clip3 = clip.loop(n=3) #loop 3 times
clip3.write_videofile(os.path.join(TMP_DIR, "loop3.webm"))
示例12: test_resize
def test_resize():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm")
clip1=clip.resize( (460,720) ) # New resolution: (460,720)
assert clip1.size == (460,720)
clip1.write_videofile(os.path.join(TMP_DIR, "resize1.webm"))
clip2=clip.resize(0.6) # width and heigth multiplied by 0.6
assert clip2.size == (clip.size[0]*0.6, clip.size[1]*0.6)
clip2.write_videofile(os.path.join(TMP_DIR, "resize2.webm"))
clip3=clip.resize(width=800) # height computed automatically.
assert clip3.w == 800
#assert clip3.h == ??
clip3.write_videofile(os.path.join(TMP_DIR, "resize3.webm"))
示例13: ffwd_video
def ffwd_video(path_in, path_out, checkpoint_dir, device_t='/gpu:0', batch_size=4):
video_clip = VideoFileClip(path_in, audio=False)
video_writer = ffmpeg_writer.FFMPEG_VideoWriter(path_out, video_clip.size, video_clip.fps, codec="libx264",
preset="medium", bitrate="2000k",
audiofile=path_in, threads=None,
ffmpeg_params=None)
g = tf.Graph()
soft_config = tf.ConfigProto(allow_soft_placement=True)
soft_config.gpu_options.allow_growth = True
with g.as_default(), g.device(device_t), \
tf.Session(config=soft_config) as sess:
batch_shape = (batch_size, video_clip.size[1], video_clip.size[0], 3)
img_placeholder = tf.placeholder(tf.float32, shape=batch_shape,
name='img_placeholder')
preds = transform.net(img_placeholder)
saver = tf.train.Saver()
if os.path.isdir(checkpoint_dir):
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
else:
raise Exception("No checkpoint found...")
else:
saver.restore(sess, checkpoint_dir)
X = np.zeros(batch_shape, dtype=np.float32)
def style_and_write(count):
for i in range(count, batch_size):
X[i] = X[count - 1] # Use last frame to fill X
_preds = sess.run(preds, feed_dict={img_placeholder: X})
for i in range(0, count):
video_writer.write_frame(np.clip(_preds[i], 0, 255).astype(np.uint8))
frame_count = 0 # The frame count that written to X
for frame in video_clip.iter_frames():
X[frame_count] = frame
frame_count += 1
if frame_count == batch_size:
style_and_write(frame_count)
frame_count = 0
if frame_count != 0:
style_and_write(frame_count)
video_writer.close()
示例14: loadMovie
def loadMovie(self, filename, log=True):
"""Load a movie from file
:Parameters:
filename: string
The name of the file, including path if necessary
After the file is loaded MovieStim.duration is updated with the movie
duration (in seconds).
"""
self.reset() #set status and timestamps etc
# Create Video Stream stuff
if os.path.isfile(filename):
self._mov = VideoFileClip(filename, audio= (1-self.noAudio))
if (not self.noAudio) and (self._mov.audio is not None):
self._audioStream = sound.Sound(self._mov.audio.to_soundarray(),
sampleRate = self._mov.audio.fps)
else: #make sure we set to None (in case prev clip did have auido)
self._audioStream = None
else:
raise IOError("Movie file '%s' was not found" %filename)
#mov has attributes:
# size, duration, fps
#mov.audio has attributes
#duration, fps (aka sampleRate), to_soundarray()
self._frameInterval = 1.0/self._mov.fps
self.duration = self._mov.duration
self.filename = filename
self._updateFrameTexture()
logAttrib(self, log, 'movie', filename)
示例15: __init__
def __init__(self, filename, onset=None):
self.clip = VideoFileClip(filename)
self.fps = self.clip.fps
self.width = self.clip.w
self.height = self.clip.h
self.n_frames = int(self.fps * self.clip.duration)
duration = self.clip.duration
super(VideoStim, self).__init__(filename, onset, duration)