Reputation: 305
I was wondering how to run a loop so that all the videos in a file have their frames extracted and saved to a new file. So far I have the following code:
import cv2
import os
# where the videos are stored
path = "/Users/harryhat/Desktop/Water Droplets/Videos of water droplets/Random"
for video_path in os.listdir(path):
name, ext = os.path.splitext(video_path)
if ext == '.avi':
video_path = os.path.join(path, video_path)
# Opens the Video file
cap = cv2.VideoCapture(video_path)
i = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret == False:
break
cv2.imwrite(str(name)+str(i)+'.jpg', frame)
i += 1
cap.release()
cv2.destroyAllWindows()
However at the moment when I run it nothing happened, ideally each video would have their frames extracted and placed in a file which had the videos name in it. Any pointers on how to achieve this?
Upvotes: 0
Views: 881
Reputation:
you do in this way
import cv2
import os
count=1
vidcap = cv2.VideoCapture('video.mp4')
def getFrame(sec):
vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
hasFrames,image = vidcap.read()
if hasFrames:
dim = (512, 512) # you can change image height and image width
resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
cv2.imwrite("images/"+str(count)+".png", resized) # image write to image folder be sure crete image folder in same dir
return hasFrames
sec = 0
frameRate = 0.1 # change frame rate as you wish, ex : 30 fps => 1/30
success = getFrame(sec)
while success:
count = count + 1
sec = sec + frameRate
sec = round(sec, 2)
success = getFrame(sec)
If this helps you give 👍
Upvotes: 1