redpd
redpd

Reputation: 17

How to save frames every nth second, in OpenCV

I'm trying to save a frame every 0.05 sec but my solution doesn't seem to work. What changes should I make to my code?

fps = 18 rate = 1/18 or 0.05

source = "video.mp4"
cap = cv2.VideoCapture('source/%s' % source)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = int(cap.get(cv2.CAP_PROP_FPS))


count = 0
rate = round((1/fps), 3) - 0.006 # rounds to 0.05 sec
# 1 frame = 0.05 sec -> 18 frames = 0.9 or 1 sec
sec = 0
# 0.5
# 0.1
# 0.15
# ...

while True:
    sec = sec + rate
    cap.set(cv2.CAP_PROP_POS_MSEC, sec*1000) # sec*1000 converts to ms
    ret, frame = cap.read() 
    if not ret:
        cap.release()
        break
    else:
        cv2.imwrite("../frames/" + "frame%d.jpg" % count, frame)
    count += 1;

Upvotes: 1

Views: 1910

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

If you use this:

cap.set(cv2.CAP_PROP_POS_MSEC, sec*1000)

inside your loop, you are effectively trying to seek (i.e. set your position) backwards and forwards inside your video in order to read each frame. I think you'll do much better reading all the frames in a linear fashion and discarding the ones you don't want, so if the frame rate is 60fps and you want 15fps, just save every 4th frame:

if frameCounter % 4 == 0:
    cv2.imwrite(...)

Upvotes: 1

Related Questions