当前位置:   article > 正文

python视频帧转图像与图像生成视频_video2frame-frame2video

video2frame-frame2video

用python实现将视频中的帧保存为图像。

video2frames.py

  1. import cv2
  2. import os
  3. def video2frames(videofile, savepath):
  4. vcap = cv2.VideoCapture()
  5. vcap.open(videofile)
  6. n = 1
  7. frame_interval = 12 # 每隔frame_interval帧保存图像
  8. total_frames = int(vcap.get(cv2.CAP_PROP_FRAME_COUNT))
  9. print(f'total frames: {total_frames}') # 267
  10. for i in range(total_frames):
  11. ret, frame = vcap.read()
  12. if i % frame_interval == 0:
  13. filename = videofile.split('.')[-1] + '_' + str(n) + '.jpg'
  14. print(filename)
  15. # 保存当前帧图像,以下两个方式都可以
  16. cv2.imencode('.jpg', frame)[1].tofile(os.path.join(savepath, filename))
  17. # cv2.imwrite(os.path.join(savepath, filename), frame)
  18. n += 1
  19. vcap.release()
  20. if __name__ == '__main__':
  21. savepath = './frames'
  22. videofile = 'demo.mp4'
  23. video2frames(videofile, savepath)

用python实现将文件夹中的图像生成视频。

frames2video.py

  1. import os
  2. import cv2
  3. import glob
  4. def video2frames(imgspath, savepath):
  5. out_vid = None
  6. imgfiles = sorted(glob.glob(os.path.join(imgspath, '*.*')))
  7. for imgfile in imgfiles:
  8. print(imgfile)
  9. img = cv2.imread(imgfile)
  10. savefile = os.path.join(savepath, 'test.mp4')
  11. if out_vid is None:
  12. out_vid = cv2.VideoWriter(savefile, cv2.VideoWriter_fourcc(*'mp4v'), 12, (img.shape[1], img.shape[0]))
  13. out_vid.write(img)
  14. out_vid.release()
  15. if __name__ == '__main__':
  16. savepath = './'
  17. imgspath = './images/'
  18. video2frames(imgspath, savepath)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/944747
推荐阅读
相关标签
  

闽ICP备14008679号