简体   繁体   中英

How do I decrease number of frames in OpenCV python?

I'm using python and opencv to work with the frame. I'm following the code below which saves frame in a directory. I have a problem that even if the video is 1 second I get more than 1000 frames.

Can anyone help me how to decrease the number of frames?

import cv2
import os 
cap = cv2.VideoCapture('7.mp4') 
currentFrame = 0
ret, frame = cap.read()
current_dir=os.getcwd()
while ret:
 name = current_dir+'/pic2/frame' + str(currentFrame) + '.jpg'
 print(name)
 cv2.imwrite(name,frame)
 currentFrame+=1

You are reading 1 frame and then, because ret==True , you are in an infinite loop, saving the same frame over and over. As you can see on the tutorials , you should do something like this:

import os
import cv2

cap = cv2.VideoCapture('7.mp4') 

currentFrame = 0
current_dir = os.getcwd()
while True:                   # infinite loop
    ret, frame = cap.read()   # read frame-by-frame
    if not ret:               # if read fails
        break                 # break the loop
    name = os.path.join(current_dir, 'pic', 'frame{}.jpg'.format(currentFrame))
    print(name)
    cv2.imwrite(name, frame)
    currentFrame += 1

cap.release()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM