Python - Extracting distinct/unique frames from Videos

Viewed 2194

I'm trying to extract distinct frames from videos. I used opencv(code below) which lets me extract all the frames from a video but what I'm looking for are unique images which don't overlap each other. Any suggestions? TIA.

import cv2
import os

video = cv2.VideoCapture("INPUT.MOV")

currFrame =0

while(True):
   ret,frame = video.read()

   if ret:
       name = './data/frame'+ str(currFrame) + '.jpg'

       cv2.imwrite(name, frame)

       currFrame += 1
   else:
       break

video.release()
cv2.destroyAllWindows()

EDIT: it's a continuous video. For example, https://www.youtube.com/watch?v=JBLQbOG8Z1Y , in this, I need the separate shots of the skyline i.e, one at the 1st second and one at 6th second.

1st Second
6th Second

1 Answers

If you want second-wise, you can divide the code and check for the first frame of every second (Frames per second)

video = cv2.VideoCapture("INPUT.MOV")
  
try:
    # creating a folder named data
    if not os.path.exists('secondWiseData'):
        os.makedirs('secondWiseData')

except OSError:
    print ('Error: Creating directory of data')

currentframe = 0

#Check the version of opencv you are using
# Find OpenCV version

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')

# if int(major_ver)  < 3 :
fps = int(video.get(cv2.cv.CV_CAP_PROP_FPS))
#Else    
fps = int(video.get(cv2.CAP_PROP_FPS))

#The FPS generated could be decimal as well. We get its greatest interger function by casting to int().

print('The FPS of the video is ', str(fps))
time_start=time.time()
    
while(True):
      
    # reading from frame
    ret,frame = cam.read()
  
    if ret:
        # if video is still left continue creating images
        name = './secondWiseData/frame' + str(currentframe) + '.jpg'
        
        if currentframe % fps == 1: 
            print ('Creating...' + name)
            cv2.imwrite(name, frame)
            currentframe += 1
            continue
        else:
            currentframe += 1
            continue
  
        # increasing counter so that it will
        # show how many frames are created
        
    else:
        break

time_end=time.time()
print('Total time taken is ', time_end-time_start)    
print('Total frames are ', currentframe)

#Release all space and windows once done
cam.release()
cv2.destroyAllWindows()

This will give you the frames of every second in the video considered.

Related