删除视频中相同或者相似的帧 | Python opencv - 图1
© Chris Conlan

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Basic Grammars of OpenCV: Karobben Blog

So, the situation is, after you recorded a video, there are lots of nonsense frames when you are doing something else, drinking water for instance. By calculating the difference between each frame with the previous frame, we can get a list of numbers and tossing the frame with low value by looking into this list.

import library

  1. import cv2
  2. import matplotlib.pyplot as plt

Reading Video

With the Code below, you can load and show the video on window “video”

  1. Video = "test2.mp4"
  2. cap=cv2.VideoCapture(Video)
  3. while (True):
  4. ret,frame=cap.read()
  5. cv2.imshow("video",frame)
  6. # 在播放每一帧时,使用cv2.waitKey()设置适当的持续时间。如果设置的太低视频就会播放的非常快,如果设置的太高就会播放的很慢。通常情况下25ms就ok
  7. if cv2.waitKey(1)&0xFF==ord('q'):
  8. cv2.destroyAllWindows()
  9. break

Calculate the different of each frame

Calculate the difference of the images

  1. def Diff_img(img0, img):
  2. '''
  3. This function is designed for calculating the difference between two
  4. images. The images are convert it to an grey image and be resized to reduce the unnecessary calculating.
  5. '''
  6. # Grey and resize
  7. img0 = cv2.cvtColor(img0, cv2.COLOR_RGB2GRAY)
  8. img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  9. img0 = cv2.resize(img0, (320,200), interpolation = cv2.INTER_AREA)
  10. img = cv2.resize(img, (320,200), interpolation = cv2.INTER_AREA)
  11. # Calculate
  12. Result = (abs(img - img0)).sum()
  13. return Result
  1. Video = "test2.mp4"
  2. cap=cv2.VideoCapture(Video)
  3. ret,frame0 = cap.read()
  4. Result = []
  5. Num = 0
  6. while (True):
  7. ret,frame=cap.read()
  8. #cv2.imshow("video",frame)
  9. if Num > 0:
  10. Result += [Diff_img(frame0, frame)]
  11. frame0 = frame
  12. Num += 1
  13. if cv2.waitKey(25)&0xFF==ord('q'):
  14. cv2.destroyAllWindows()
  15. break

Write result

  1. Video = "test.mp4"
  2. cap=cv2.VideoCapture(Video)
  3. ret,frame0 = cap.read()
  4. fps_c = cap.get(cv2.CAP_PROP_FPS)
  5. Video_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  6. Video_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  7. fps = fps_c
  8. size = (Video_w,Video_h)
  9. fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
  10. videowriter = cv2.VideoWriter("output.avi",fourcc,fps,size)
  11. Result = []
  12. Num = 0
  13. while (True):
  14. ret,frame=cap.read()
  15. #cv2.imshow("video",frame)
  16. if Num > 0:
  17. Diff = Diff_img(frame0, frame)
  18. Result += [Diff]
  19. frame0 = frame
  20. if Diff > 10000:
  21. videowriter.write(frame0)
  22. Num += 1
  23. print(round(Num /237450 * 100, 3))
  24. videowriter.release()

The compare of the video before (left) and after (right) processing.
删除视频中相同或者相似的帧 | Python opencv - 图2


Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗