用于读取视频帧的OpenCV实用程序
videoutils的Python项目详细描述
OpenCV的视频实用程序
videoutils
lets you get rid of writing boilerplate code for reading video and adds some convenience on top of that.
安装
pip install videoutils
如何使用
fromvideoutils.ioimportread_video,as_tensor,bgr2rgb,resizefname='files/interstellar-waves-edit.mp4'
^{pr2}$
1578
(480, 720, 3)
默认情况下,read_video
返回形状为(height, width, channels)
的np.array
的列表。
但是,您可以通过多种方式精确地定义要抓取的帧。这可以通过使用{{end_idx
、frame_stride
}或{
抓取第一个n
帧
n=50x=read_video(fname,end_idx=n)x2=read_video(fname,target_frames=(0,n))len(x)len(x)==len(x2)
50
True
每隔第n
帧抓取
n=5x=read_video(fname,frame_stride=n,end_idx=50)len(x)
10
x=read_video(fname,frame_stride=50)# total frames = 1578len(x)
32
特定指标下的抓斗框架
x=read_video(fname,target_frames=[10,50,76,420])len(x)
4
x=read_video(fname,start_idx=10,end_idx=15)x2=read_video(fname,target_frames=(10,15))len(x)len(x)==len(x2)
5
True
返回为torch.Tensor
您可以传递任何将形状(height, width, channels)
的np.array
转换为apply
参数的函数。videoutils
提供as_tensor
为方便起见——如果使用此函数,read_video
将自动调用torch.stack
,并以4D张量的形式返回帧集合,否则它将返回3D数组/张量的list
。在
importtorchfromfunctoolsimportpartialx=read_video(fname,end_idx=10,apply=as_tensor)x2=read_video(fname,end_idx=10,apply=partial(as_tensor,normalise=True))x2=torch.stack(x2)# since we aren't using `as_tensor`, but a partial (thus different) functionx.shapex.shape==x2.shapex.mean(),x2.mean()
torch.Size([10, 480, 720, 3])
True
(tensor(36.8276), tensor(0.1443))
调整视频大小
read_video
有一个可选参数resize_func
,这意味着它是一个调整形状(height, width, channels)
的np.array
大小的函数。
您可以使用预定义的resize
函数或在此处传入自定义函数。在
help(resize)
Help on function resize in module videoutils.utils:
resize(image, height=None, width=None, keep_aspect_ratio=True, scale_factor=1.0)
Resize by `scale_factor` if preserving aspect ratio else
resize by custom `height` and `width`
x=read_video(fname,target_frames=[0,1,2],apply=as_tensor,resize_func=partial(resize,scale_factor=2.))x.shape
torch.Size([3, 960, 1440, 3])
x=read_video(fname,target_frames=[0,1,2],apply=as_tensor,resize_func=partial(resize,width=200,height=100,keep_aspect_ratio=False))x.shape
^{pr21}$
- 项目
标签: