当前位置:   article > 正文

Python之OpenCV读取视频抽帧保存_if i%interval == 0:

if i%interval == 0:

=================== 20200701更新 ======================= 

  1. # -*- coding:utf8 -*-
  2. import cv2
  3. import os
  4. import shutil
  5. def get_frame_from_video(video_name, interval):
  6. """
  7. Args:
  8. video_name:输入视频名字
  9. interval: 保存图片的帧率间隔
  10. Returns:
  11. """
  12. # 保存图片的路径
  13. save_path = video_name.split('.mp4')[0] + '/'
  14. is_exists = os.path.exists(save_path)
  15. if not is_exists:
  16. os.makedirs(save_path)
  17. print('path of %s is build' % save_path)
  18. else:
  19. shutil.rmtree(save_path)
  20. os.makedirs(save_path)
  21. print('path of %s already exist and rebuild' % save_path)
  22. # 开始读视频
  23. video_capture = cv2.VideoCapture(video_name)
  24. i = 0
  25. j = 0
  26. while True:
  27. success, frame = video_capture.read()
  28. i += 1
  29. if i % interval == 0:
  30. # 保存图片
  31. j += 1
  32. save_name = save_path + str(j) + '_' + str(i) + '.jpg'
  33. cv2.imwrite(save_path + save_name, frame)
  34. print('image of %s is saved' % save_name)
  35. if not success:
  36. print('video is all read')
  37. break
  38. if __name__ == '__main__':
  39. # 视频文件名字
  40. video_name = './00156/00156.mp4'
  41. interval = 10
  42. get_frame_from_video(video_name, interval)

=================== 原始内容 ======================= 

  1. # -*- coding:utf8 -*-
  2. import cv2
  3. import os
  4. import shutil
  5. #视频文件名字
  6. filename = '00156.mp4'
  7. #保存图片的路径
  8. savedpath = filename.split('.')[0] + '/'
  9. isExists = os.path.exists(savedpath)
  10. if not isExists:
  11. os.makedirs(savedpath)
  12. print('path of %s is build'%(savedpath))
  13. else:
  14. shutil.rmtree(savedpath)
  15. os.makedirs(savedpath)
  16. print('path of %s already exist and rebuild'%(savedpath))
  17. #视频帧率12
  18. fps = 12
  19. #保存图片的帧率间隔
  20. count = 60
  21. #开始读视频
  22. videoCapture = cv2.VideoCapture(filename)
  23. i = 0
  24. j = 0
  25. while True:
  26. success,frame = videoCapture.read()
  27. i+=1
  28. if(i % count ==0):
  29. #保存图片
  30. j += 1
  31. savedname = filename.split('.')[0] + '_' + str(j) + '_' + str(i)+'.jpg'
  32. cv2.imwrite(savedpath + savedname ,frame)
  33. print('image of %s is saved'%(savedname))
  34. if not success:
  35. print('video is all read')
  36. break

 

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

闽ICP备14008679号