转载于:https://blog.csdn.net/Bit_Coders/article/details/114084851
mmcv简介
mmcv是商汤科技用于计算机视觉研究的基础python库,API比opencv更简洁,很适合深度学习项目的图像、视频预处理。
安装mmcv依赖库:
pip install mmcv
常用代码:
#加载视频
video = mmcv.VideoReader('test.mp4')
# 迭代访问所有帧
for frame in video:
print(frame.shape)
# read the next frame
img = video.read()
# read a frame by index
img = video[100]
# read some frames
imgs = video[5:10]
视频转图像
1、mmcv
如果不需要对视频帧进行处理,直接调用cvt2frames接口,是最简洁的
# split a video into frames and save to a folder
video = mmcv.VideoReader('test.mp4')
video.cvt2frames('out_dir')
如果需要对视频帧进行处理,如resize等操作
# 将视频转成图片序列后的分辨率
new_width = 224
new_height = 224
# 读取视频
video = mmcv.VideoReader('test.mp4')
for i in range(len(video)):
if video[i] is not None:
# 获取每一帧的width、height和channel
w, h, c = np.shape(video[i])
# 改变图片分辨率
if new_width>0 and new_height>0:
out_img = mmcv.imresize(video[i], (new_width,new_height))
else:
out_img = video[i]
mmcv.imwrite(out_img,os.path.join('out_dir','img_%05d.jpg'%i))
else:
warnings.warn(
'Length inconsistent!'
f'Early stop with {i + 1} out of {len(vr)} frames.')
break
2、opencv
# opencv版本的视频转图像序列
cap = cv2.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
imgs = []
while True:
ret, img = cap.read()
if ret == False:
break
imgs.append(img)
cv2.imshow('capture %d' % i, img)
ch = cv2.waitKey(1)
if ch == 27:
break
cv2.destroyAllWindows()
for i, img in enumerate(imgs):
fn = '%s/shot_%03d.bmp' % (save_dir, i)
cv2.imwrite(fn, img)
#print(fn, 'saved')
图像序列转视频
mmcv
# generate video from frames
mmcv.frames2video('out_dir', 'test.avi')
# 剪辑视频 cut a video clip
mmcv.cut_video('test.mp4', 'clip1.mp4', start=3, end=10, vcodec='h264')
# join a list of video clips拼接视频
mmcv.concat_video(['clip1.mp4', 'clip2.mp4'], 'joined.mp4', log_level='quiet')
修改视频尺寸/分辨率
# resize a video with the specified size
mmcv.resize_video('test.mp4', 'resized1.mp4', (360, 240))
# resize a video with a scaling ratio of 2
mmcv.resize_video('test.mp4', 'resized2.mp4', ratio=2)
感觉很有用!!!!!!
gooooood!!!!
转载于:https://blog.csdn.net/Bit_Coders/article/details/114084851