本文整理汇总了Python中moviepy.video.io.VideoFileClip.VideoFileClip类的典型用法代码示例。如果您正苦于以下问题:Python VideoFileClip类的具体用法?Python VideoFileClip怎么用?Python VideoFileClip使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VideoFileClip类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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'))
开发者ID:chaosct,项目名称:repoVizzRecorder,代码行数:25,代码来源:repoVizzRecorder.py
示例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')
开发者ID:codelucas,项目名称:vsummarize,代码行数:25,代码来源:video.py
示例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())
开发者ID:Zulko,项目名称:moviepy,代码行数:7,代码来源:test_VideoClip.py
示例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())
开发者ID:Zulko,项目名称:moviepy,代码行数:7,代码来源:test_VideoClip.py
示例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))
开发者ID:qmac,项目名称:featureX,代码行数:31,代码来源:video.py
示例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
开发者ID:QUVA-Lab,项目名称:artemis,代码行数:31,代码来源:smart_io.py
示例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())
开发者ID:Zulko,项目名称:moviepy,代码行数:8,代码来源:test_VideoClip.py
示例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())
开发者ID:Zulko,项目名称:moviepy,代码行数:8,代码来源:test_VideoClip.py
示例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.")
开发者ID:Zulko,项目名称:moviepy,代码行数:58,代码来源:test_resourcereleasedemo.py
示例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())
开发者ID:Zulko,项目名称:moviepy,代码行数:9,代码来源:test_VideoClip.py
示例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"))
开发者ID:Mediaeater,项目名称:moviepy,代码行数:13,代码来源:test_fx.py
示例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"))
开发者ID:Mediaeater,项目名称:moviepy,代码行数:15,代码来源:test_fx.py
示例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()
开发者ID:XingXL,项目名称:fast-style-transfer,代码行数:48,代码来源:evaluate.py
示例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)
开发者ID:papr,项目名称:psychopy,代码行数:33,代码来源:movie3.py
示例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)
开发者ID:qmac,项目名称:featureX,代码行数:11,代码来源:video.py
示例16: download_and_convert
def download_and_convert(url):
print("converting url " + url)
source = pafy.new(url)
best = source.getbest(preftype="mp4")
ts = datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d-%H%M%S')
input_filename = "/tmp/" + ts + "." + best.extension
best.download(filepath=input_filename)
output = VideoFileClip(input_filename)
duration = output.duration
output_filename="/tmp/" + best.title + "." + best.extension
output = output.set_audio(audio).fl_time(lambda t: t * accel, apply_to='mask').set_duration(duration / accel)
output.write_videofile(output_filename)
print("uploading to s3")
s3 = boto.connect_s3()
bucket = s3.get_bucket('bennyhill')
key = Key(bucket)
key.key = best.title + "-" + ts
key.set_contents_from_filename(output_filename)
output_url = key.generate_url(expires_in=3600)
print("complete")
# save the results
try:
result = Result(
url=url,
youtube_url=output_url
)
db.session.add(result)
db.session.commit()
return result.id
except:
errors.append("Unable to add item to database.")
return {"error": errors}
开发者ID:xuloo,项目名称:bennyhillmachine,代码行数:40,代码来源:app.py
示例17: 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).
"""
filename = pathToString(filename)
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):
sound = self.sound
try:
self._audioStream = sound.Sound(
self._mov.audio.to_soundarray(),
sampleRate=self._mov.audio.fps)
except:
# JWE added this as a patch for a moviepy oddity where the
# duration is inflated in the saved file causes the
# audioclip to be the wrong length, so round down and it
# should work
jwe_tmp = self._mov.subclip(0, round(self._mov.duration))
self._audioStream = sound.Sound(
jwe_tmp.audio.to_soundarray(),
sampleRate=self._mov.audio.fps)
del(jwe_tmp)
else: # make sure we set to None (in case prev clip had audio)
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)
开发者ID:dgfitch,项目名称:psychopy,代码行数:46,代码来源:movie3.py
示例18: test_ffmpeg_resizing
def test_ffmpeg_resizing():
"""Test FFmpeg resizing, to include downscaling."""
video_file = 'media/big_buck_bunny_432_433.webm'
target_resolution = (128, 128)
video = VideoFileClip(video_file, target_resolution=target_resolution)
frame = video.get_frame(0)
assert frame.shape[0:2] == target_resolution
target_resolution = (128, None)
video = VideoFileClip(video_file, target_resolution=target_resolution)
frame = video.get_frame(0)
assert frame.shape[0] == target_resolution[0]
target_resolution = (None, 128)
video = VideoFileClip(video_file, target_resolution=target_resolution)
frame = video.get_frame(0)
assert frame.shape[1] == target_resolution[1]
# Test upscaling
target_resolution = (None, 2048)
video = VideoFileClip(video_file, target_resolution=target_resolution)
frame = video.get_frame(0)
assert frame.shape[1] == target_resolution[1]
开发者ID:bobatsar,项目名称:moviepy,代码行数:23,代码来源:test_VideoFileClip.py
示例19: load_media
def load_media(self, mediafile, play_audio=True):
""" Loads a media file to decode.
If an audiostream is detected, its parameters will be stored in a
dictionary in the variable `audioformat`. This contains the fields
:nbytes: the number of bytes in the stream (2 is 16-bit sound).
:nchannels: the channels (2 for stereo, 1 for mono)
:fps: the frames per sec/sampling rate of the sound (e.g. 44100 KhZ).
:buffersize: the audioframes per buffer.
If play_audio was set to False, or the video does not have an audiotrack,
`audioformat` will be None.
Parameters
----------
mediafile : str
The path to the media file to load.
play_audio : bool, optional
Indicates whether the audio of a movie should be played.
Raises
------
IOError
When the file could not be found or loaded.
"""
if not mediafile is None:
if os.path.isfile(mediafile):
self.clip = VideoFileClip(mediafile, audio=play_audio)
self.loaded_file = os.path.split(mediafile)[1]
## Timing variables
# Clip duration
self.duration = self.clip.duration
self.clock.max_duration = self.clip.duration
logger.debug("Video clip duration: {}s".format(self.duration))
# Frames per second of clip
self.fps = self.clip.fps
self.clock.fps = self.clip.fps
logger.debug("Video clip FPS: {}".format(self.fps))
if play_audio and self.clip.audio:
buffersize = int(self.frame_interval*self.clip.audio.fps)
self.audioformat = {
'nbytes': 2,
'nchannels': self.clip.audio.nchannels,
'fps': self.clip.audio.fps,
'buffersize': buffersize
}
logger.debug("Audio loaded: \n{}".format(self.audioformat))
logger.debug("Creating audio buffer of length: "
" {}".format(queue_length))
self.audioqueue = Queue(queue_length)
else:
self.audioformat = None
logger.debug('Loaded {0}'.format(mediafile))
self.status = READY
return True
else:
raise IOError("File not found: {0}".format(mediafile))
return False
开发者ID:fladd,项目名称:python-mediadecoder,代码行数:64,代码来源:decoder.py
示例20: test_withoutaudio
def test_withoutaudio():
clip = VideoFileClip("media/big_buck_bunny_432_433.webm").subclip(0.2, 0.6)
new_clip = clip.without_audio()
assert new_clip.audio is None
close_all_clips(locals())
开发者ID:Zulko,项目名称:moviepy,代码行数:5,代码来源:test_VideoClip.py
注:本文中的moviepy.video.io.VideoFileClip.VideoFileClip类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论