How does python extract picture per second from video

  • 2021-07-26 08:17:47
  • OfStack

I need to change a video into a picture data set in pedestrian detection, and then I want to extract the pictures of the video every second.

Language: python Required libraries: cv2, numpy (self-installed)

opencv provides a function to read every frame of video, and the following code can extract every frame of video. Note: My video name is 2. mp4, and I need to build a folder named output to extract the picture and save the directory.


#  Import the required libraries 
import cv2
import numpy as np
 
#  Define the Save Picture function 
# image: The name of the picture to save 
# addr ; The first part of the picture address and photo name 
# num:  Photo, suffix of name. int  Type 
def save_image(image,addr,num):
 address = addr + str(num)+ '.jpg'
 cv2.imwrite(address,image)
 
#  Read a video file 
videoCapture = cv2.VideoCapture("2.mp4")
#  By means of cameras 
# videoCapture=cv2.VideoCapture(1)
 
# Read frame 
success, frame = videoCapture.read()
i = 0
while success :
 i = i + 1
 save_image(frame,'./output/image',m)
 if success : 
  print('save image:',i)
 success, frame = videoCapture.read()

Now I want to extract by seconds, as long as we can know how many frames the video has per second, and then extract it every so many frames based on the above code, which requires looking at the frame rate of the video. 1 Under normal circumstances, you can see the frame rate by right-clicking on the video after opening it with one player. Now my video frame rate is 12, and I can get pictures per second by extracting every 12 frames. The code is as follows:


#  Import the required libraries 
import cv2
import numpy as np
 
#  Define the Save Picture function 
# image: The name of the picture to save 
# addr ; The first part of the picture address and photo name 
# num:  Photo, suffix of name. int  Type 
def save_image(image,addr,num):
 address = addr + str(num)+ '.jpg'
 cv2.imwrite(address,image)
 
#  Read a video file 
videoCapture = cv2.VideoCapture("2.mp4")
#  By means of cameras 
# videoCapture=cv2.VideoCapture(1)
 
# Read frame 
success, frame = videoCapture.read()
i = 0
timeF = 12
j=0
while success :
 i = i + 1
 if (i % timeF == 0):
  j = j + 1
  save_image(frame,'./output/image',j)
  print('save image:',i)
 success, frame = videoCapture.read()

Related articles: