本文整理汇总了Python中moviepy.editor.VideoFileClip.iter_frames方法的典型用法代码示例。如果您正苦于以下问题:Python VideoFileClip.iter_frames方法的具体用法?Python VideoFileClip.iter_frames怎么用?Python VideoFileClip.iter_frames使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类moviepy.editor.VideoFileClip
的用法示例。
在下文中一共展示了VideoFileClip.iter_frames方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: average_video
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
def average_video(filepath, outpath, start=None, end=None, sample_every=1):
"""Calculate average of video frames"""
# Load video
vid = VideoFileClip(filepath, audio=False)
width = vid.w
height = vid.h
if start is None and end is None:
frame_generator = vid.iter_frames(progress_bar=True, dtype=np.uint8)
else:
if start is None:
start = 0
if end is None:
end = vid.duration
# compute time increment for sampling by frames
sample_inc = sample_every / vid.fps
frame_generator = tqdm(vid.get_frame(f) for f in frange(start, end, sample_inc))
# create starting matrix of zeros
sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
ma_sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
prev_f = np.zeros(shape=(height, width, 3), dtype=int)
sum_delta_fs = np.zeros(shape=(height, width, 3), dtype=int)
n_frames = 0
for f in frame_generator:
delta = f - prev_f
sum_delta_fs += delta
sum_fs += f
ma_sum_fs += f
if divmod(n_frames, 100)[1] == 0 and n_frames > 0:
ma_f = ma_sum_fs / 100
Image.fromarray(ma_f.astype(np.uint8))\
.save(os.path.join(outpath, 'movavg_{}.png'.format(n_frames)))
ma_sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
n_frames += 1
prev_f = f
# average out the values for each frame
average_delta_f = sum_delta_fs / n_frames
average_f = sum_fs / n_frames
# Create images
delta_img = Image.fromarray(average_delta_f.astype(np.uint8))
delta_img.save(os.path.join(outpath, 'average_delta.png'))
final_img = Image.fromarray(average_f.astype(np.uint8))
final_img.save(os.path.join(outpath, 'average.png'))
示例2: average_video
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
def average_video(filepath, outpath, start=None, end=None, sample_every=1):
"""Calculate average of video frames"""
# Load video
vid = VideoFileClip(filepath, audio=False).resize(width=66)
width = vid.w
height = vid.h
if start is None and end is None:
frame_generator = vid.iter_frames(progress_bar=True, dtype=np.uint8)
else:
if start is None:
start = 0
if end is None:
end = vid.duration
# compute time increment for sampling by frames
sample_inc = sample_every / vid.fps
frame_generator = tqdm(vid.get_frame(f) for f in frange(start, end, sample_inc))
# create starting matrix of zeros
sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
ma_sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
prev_f = np.zeros(shape=(height, width, 3), dtype=int)
sum_delta_fs = np.zeros(shape=(height, width, 3), dtype=int)
n_frames = 0
for f in frame_generator:
#delta = f - prev_f
#sum_delta_fs += delta
#sum_fs += f
#ma_sum_fs += f
#if divmod(n_frames, 100)[1] == 0 and n_frames > 0:
# ma_f = ma_sum_fs / 100
# Image.fromarray(ma_f.astype(np.uint8))\
# .save(os.path.join(outpath, 'movavg_{}.png'.format(n_frames)))
# ma_sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
#n_frames += 1
#prev_f = f
print len(f)
time.sleep(1.0/float(sample_every))
示例3: run_moving_crash
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
def run_moving_crash(args, target, outfile):
"""Runs a moving crash based on moving (gif/mp4) inputs"""
video = VideoFileClip(target)
img = video.get_frame(t=0) # first frame of the video
bounds = foreground.get_fg_bounds(img.shape[1], args.max_depth)
max_depth = bounds.max_depth
crash_params = crash.CrashParams(
max_depth, args.threshold, args.bg_value, args.rgb_select)
options = _options(args.reveal_foreground, args.reveal_background,
args.crash, args.reveal_quadrants, args.bg_value)
frames = video.iter_frames(fps=video.fps)
def make_frame(_):
frame = next(frames)
fg, bounds = foreground.find_foreground(frame, crash_params)
return _process_img(frame, fg, bounds, options)
output_video = VideoClip(
make_frame, duration=video.duration-(4/video.fps)) # trim last 4 frms
output_video.write_videofile(
outfile, preset=args.compression, fps=video.fps,
threads=args.in_parallel)
示例4: extract_features
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
def extract_features(input_dir, output_dir, model_type='inceptionv3', batch_size=32):
"""
Extracts features from a CNN trained on ImageNet classification from all
videos in a directory.
Args:
input_dir (str): Input directory of videos to extract from.
output_dir (str): Directory where features should be stored.
model_type (str): Model type to use.
batch_size (int): Batch size to use when processing.
"""
input_dir = os.path.expanduser(input_dir)
output_dir = os.path.expanduser(output_dir)
if not os.path.isdir(input_dir):
sys.stderr.write("Input directory '%s' does not exist!\n" % input_dir)
sys.exit(1)
# Load desired ImageNet model
# Note: import Keras only when needed so we don't waste time revving up
# Theano/TensorFlow needlessly in case of an error
model = None
input_shape = (224, 224)
if model_type.lower() == 'inceptionv3':
from keras.applications import InceptionV3
model = InceptionV3(include_top=True, weights='imagenet')
elif model_type.lower() == 'xception':
from keras.applications import Xception
model = Xception(include_top=True, weights='imagenet')
elif model_type.lower() == 'resnet50':
from keras.applications import ResNet50
model = ResNet50(include_top=True, weights='imagenet')
elif model_type.lower() == 'vgg16':
from keras.applications import VGG16
model = VGG16(include_top=True, weights='imagenet')
elif model_type.lower() == 'vgg19':
from keras.applications import VGG19
model = VGG19(include_top=True, weights='imagenet')
else:
sys.stderr.write("'%s' is not a valid ImageNet model.\n" % model_type)
sys.exit(1)
if model_type.lower() == 'inceptionv3' or model_type.lower() == 'xception':
shape = (299, 299)
# Get outputs of model from layer just before softmax predictions
from keras.models import Model
model = Model(model.inputs, output=model.layers[-2].output)
# Create output directories
visual_dir = os.path.join(output_dir, 'visual') # RGB features
#motion_dir = os.path.join(output_dir, 'motion') # Spatiotemporal features
#opflow_dir = os.path.join(output_dir, 'opflow') # Optical flow features
for directory in [visual_dir]:#, motion_dir, opflow_dir]:
if not os.path.exists(directory):
os.makedirs(directory)
# Find all videos that need to have features extracted
def is_video(x):
return x.endswith('.mp4') or x.endswith('.avi') or x.endswith('.mov')
vis_existing = [x.split('.')[0] for x in os.listdir(visual_dir)]
#mot_existing = [os.path.splitext(x)[0] for x in os.listdir(motion_dir)]
#flo_existing = [os.path.splitext(x)[0] for x in os.listdir(opflow_dir)]
video_filenames = [x for x in sorted(os.listdir(input_dir))
if is_video(x) and os.path.splitext(x)[0] not in vis_existing]
# Go through each video and extract features
from keras.applications.imagenet_utils import preprocess_input
for video_filename in tqdm(video_filenames):
# Open video clip for reading
try:
clip = VideoFileClip( os.path.join(input_dir, video_filename) )
except Exception as e:
sys.stderr.write("Unable to read '%s'. Skipping...\n" % video_filename)
sys.stderr.write("Exception: {}\n".format(e))
continue
# Sample frames at 1fps
fps = int( np.round(clip.fps) )
frames = [scipy.misc.imresize(crop_center(x.astype(np.float32)), shape)
for idx, x in enumerate(clip.iter_frames()) if idx % fps == fps//2]
#.........这里部分代码省略.........
示例5: VideoFileClip
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
#RUNS ON PYTHON 2
import numpy as np
import csv
from moviepy.editor import VideoFileClip
#FILE = 'videos/sample_red.MP4'
#FILE = 'videos/sample_red_with_mod.MP4'
FILE = "D:/Users/Rafael/Videos/iPhone/IMG_0537.mov"
clip = VideoFileClip(FILE)
data = clip.iter_frames(fps=None, with_times=True, progress_bar=True)
rgb_list = []
times_list = []
for time, rgb in data:
times_list.append(time)
rgb_list.append(rgb)
with open('csv/framedata.csv','wb') as fp:
a = csv.writer(fp, delimiter=',')
data = ['time','RED', 'GREEN','BLUE']
a.writerow(data)
frame_averages = []
for time, frame in zip(times_list, rgb_list):
#print(time)
示例6: rates
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
if args.length is not None:
clip = clip.set_duration(args.length)
print "Read clip, duration = %.1fs, FPS = %.1f" % (clip.duration, clip.fps)
#------------------------------------------------------------------------
# Non-integer frame rates (e.g. 29.97) cause problems when retrieving
# offsets. Round to an integer.
#------------------------------------------------------------------------
clip.fps = round(clip.fps)
#------------------------------------------------------------------------
# Transform brightnesses into a list of (offset_seconds, brightness)
#------------------------------------------------------------------------
print "Analysing brightness ...."
brightnesses = [ (index / clip.fps, round(np.mean(frame) / 255.0, args.round)) for index, frame in enumerate(clip.iter_frames()) ]
#------------------------------------------------------------------------
# Sort ascending
#------------------------------------------------------------------------
brightnesses = sorted(brightnesses, key = lambda x: ((-1 if args.reverse else 1) * x[1], x[0]))
#------------------------------------------------------------------------
# Transform into pairs of (origin_offset, destination_offset)
#------------------------------------------------------------------------
brightnesses = dict([ ("%.2f" % (index / clip.fps), value[0]) for index, value in enumerate(brightnesses) ])
print "Found %f frames" % (clip.fps * clip.duration)
#------------------------------------------------------------------------
# Filter function.
# Need two cases, for video (scalar offsets) and audio (arrays).
示例7: average_video
# 需要导入模块: from moviepy.editor import VideoFileClip [as 别名]
# 或者: from moviepy.editor.VideoFileClip import iter_frames [as 别名]
def average_video(filepath, outpath, start=None, end=None, sample_every=1):
global sb1
global sb2
global sb3
global sb4
global sb5
global sb6
global sb7
global sb8
global sb9
global sb10
global sb11
global sb12
global sb13
global sb14
global sb15
global sb16
global sb17
global sb18
global sb19
global sb20
global sb21
global sb22
global sb23
global sb24
global sb25
global sb26
global sb27
global sb28
global sb29
global sb30
global sb31
global sb32
global sb33
global sb34
global sb35
global sb36
global sb37
global sb38
global sb39
global sb40
global sb41
global sb42
global sb43
global sb44
global sb45
global sb46
global sb47
global sb48
global sb49
global sb50
global sb51
global sb52
global sb53
global sb54
global sb55
global sb56
global sb57
global sb58
global sb59
global sb60
global sb61
global sb62
global sb63
global sb64
global sb65
global sb66
"""Calculate average of video frames"""
# Load video
vid = VideoFileClip(filepath, audio=False).resize(width=66)
width = vid.w
height = vid.h
if start is None and end is None:
frame_generator = vid.iter_frames(progress_bar=True, dtype=np.uint8)
else:
if start is None:
start = 0
if end is None:
end = vid.duration
# compute time increment for sampling by frames
sample_inc = sample_every / vid.fps
frame_generator = tqdm(vid.get_frame(f) for f in frange(start, end, sample_inc))
# create starting matrix of zeros
sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
ma_sum_fs = np.zeros(shape=(height, width, 3), dtype=int)
prev_f = np.zeros(shape=(height, width, 3), dtype=int)
sum_delta_fs = np.zeros(shape=(height, width, 3), dtype=int)
n_frames = 0
for f in frame_generator:
#delta = f - prev_f
#sum_delta_fs += delta
#sum_fs += f
#ma_sum_fs += f
#if divmod(n_frames, 100)[1] == 0 and n_frames > 0:
# ma_f = ma_sum_fs / 100
#.........这里部分代码省略.........