SoFunction
Updated on 2025-03-02

How to cut videos in a certain time using Python (for example: crop every 10 seconds)

Use Python to cut videos over a certain time (for example: crop every 10 seconds)

Platform: Ubuntu 16.04
Function library: ffmpeg, subprocess
Requirements: Crop all .mp4 videos in the path path for each delta_X (10s), save them under save_path, and the cropped video is named and saved with id0001.mp4, id0002.mp4, id00003.mp4...

Notice:

1. Each video does not exceed 1 hour and the end of the video will be discarded. (Modify it according to your needs)

See the additional introduction at the end of the article for reference code.

2. Questions about path and save_path (I asked me this question today): It is best to separate it independently and have no inclusion relationships. For example: Don't see path='/home/video' save_path='/home/video/save', because my video_list gets (path) , and the files under path are all in video format. This is indeed not very robust. I don't think well, I hope it can help you :)

import subprocess
import os
path = '/home/dataset'  # Video storage directory to be cutvideo_list = (path)
delta_X = 10   # Cut every 10 secondssave_path = '/home/save'
mark = 0 
# Get the video durationdef get_length(filename):
    result = (["ffprobe", "-v", "error", "-show_entries",
                             "format=duration", "-of",
                             "default=noprint_wrappers=1:nokey=1", filename],
        stdout=,
        stderr=)
    return float()
for file_name in video_list:
	min = int(get_length((path, file_name))) // 60    # file_name video minutes 	second = int(get_length((path, file_name))) % 60    # file_name video seconds 	for i in range(min+1):
 		if second >= delta_X:   # Ensure at least one cutting 			start_time = 0
 			end_time = start_time+delta_X
 			for j in range((second//10)+1):
 				min_temp = str(i)
 				start = str(start_time)
 				end = str(end_time)
				# crop video
				# Ensure two digits				if len(str(min_temp)) == 1:
					min_temp = '0'+str(min_temp)
				if len(str(start_time)) == 1:
					start = '0'+str(start_time)
				if len(str(end_time)) == 1:
					end = '0'+str(end_time)
				# Set the name of the saved video				if len(str(mark)) < 6:
					name = '0'*(6-len(str(mark))-1)+str(mark)
				else:
					name = str(mark)
				command = 'ffmpeg -i {} -ss 00:{}:{} -to 00:{}:{} -strict -2 {}'.format((path,file_name),
												min_temp,start,min_temp,end,
												(save_path,'id'+str(name))+'.mp4')
				mark += 1
				(command)
				if i != min or (i == min and (end_time+delta_X) < second):
					start_time += delta_X
					end_time += delta_X
				elif (end_time+delta_X) <= second:
					start_time += delta_X
					end_time += delta_X
				elif (end_time+delta_X) > second:  # The last part that is insufficient delta_X will be abandoned					break

Additional introduction: Several operations for python processing videos

Two sets of picture sequence frames combine into one video (arranged left and right), and only one is combined into one by one and is modified by yourself.

Parameter description:

  • Two sets of picture sequence frames are stored in source, with the naming format

        real_1.png、real_2.png、..........

        fake_1.png、fake_2.png、...........

  • Save the synthesized video name() in file('./results').
  • size is the size of name(), note that the format is (width, height)
  • The size must correspond to the size of the picture, otherwise it will not be played.
import os
import cv2
import numpy as np
def picvideo(path,size,file,name):
    filelist = (path) # Get all sequence frames in the path    fps = 35
    file_path = (file,name)
    fourcc = cv2.VideoWriter_fourcc('I','4','2','0')
    # fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')  # mp4
    video = (file_path,fourcc,fps,size)
    real = []
    fake = []
    for item in filelist:
        # If the judgment is written according to your actual situation. If you use aaa, change it to ('aaa')        if ('real'):
            item=path+'/'+item
            (item)
        if ('fake'):
            item=path+'/'+item
            (item)
    ()
    ()
    for path1,path2 in zip(real,fake):
        img1=(path1)
        img2=(path2)
        assert ==, "shape error"
        # Use image=([img1,img2]) for vertical row        image=([img1,img2]) # horizontal row        (image)
    ()
number=2
path = 'source'
# Use size=(1024,512*number) for vertical rowsize = (1024*number,512)
file = './results'
name = ''
picvideo(path, size, file, name)
    

Calculate the FPS of a video

import cv2
if __name__ == '__main__' :
  video = ("video.mp4");
  # Find OpenCV version
  (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
  if int(major_ver) < 3 :
    fps = (.CV_CAP_PROP_FPS)
    print "Frames per second using (.CV_CAP_PROP_FPS): {0}".format(fps)
  else :
    fps = (cv2.CAP_PROP_FPS)
    print "Frames per second using (cv2.CAP_PROP_FPS) : {0}".format(fps)
  ();

Extract audio from a video

from  import *
video = VideoFileClip('test.mp4')
audio = 
audio.write_audiofile('')

Add the audio from A.mp4 to B.mp4

from  import VideoFileClip
origin_video = "A.mp4"
add_video = "B.mp4"
res_video = "res.mp4"
voice_video = VideoFileClip(origin_video)
audio = voice_video.audio
video = VideoFileClip(add_video)
new = video.set_audio(audio)
new.write_videofile(res_video)

Combine two videos with different formats (mp4,avi) into one avi (256,256*4), one size is (256,256*3), and the other size is (256,256)

import cv2
import numpy as np
import imageio
# Merge and voice3.mp4 (two videos with different formats) intopath = './results/'
video1 = imageio.get_reader('./results/')
video2 = imageio.get_reader('./results/voice3.mp4')
video1_L = []
for im in video1:
    video1_L.append(im)

video2_L = []
for im in video2:
    video2_L.append(im)

fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out1 = (path,fourcc,20,(256*4,256),True)
for frame1,frame2 in zip(video1_L ,video2_L):
    frame1 = (('float32'), cv2.COLOR_BGR2RGB)    
    frame2 = (('float32'), cv2.COLOR_BGR2RGB) 
    # For videos of different formats, the following steps are crucial    frame1 = (np.uint8)
    frame2 = (np.uint8)
    image = ((frame1,frame2),axis=1)
    (image)

Resize the image in a folder to (256,256), and convert jpg to png

import 
import os
path = './data'
path_list = (path)
for file in path_list:
    im = ((path,file))
    im = ((256,256))
    ((path,file[:-3]+'png'))
    ((path,file))

Save video test.mp4 (for example: 00:00:01-00:05:00) as crop.mp4 (need to install ffmpeg)

ffmpeg -i test.mp4 -ss 00:00:01 -to 00:05:00 -c:v copy -c:a copy crop.mp4

If the black video occurs using the above command, use the following command

ffmpeg -i test.mp4 -ss 00:00:01 -to 00:05:00 -strict -2 crop.mp4

Save the video test.mp4 image every 5 seconds (1 picture is saved when fps=1, and 5 seconds is saved when fps=1/5=0.2)

ffmpeg -i test.mp4 -vf fps&#61;0.2 out%

Rotate the video (moviepy is required)

from  import *
clip = VideoFileClip("result.mp4")
# clip = (-90) # Rotate 90 clockwiseclip = (90) # 90 counterclockwiseclip.write_videofile("res.mp4")  # save

The duration of the video (calculated in seconds)

import subprocess
def get_length(filename):
    result = (["ffprobe", "-v", "error", "-show_entries",
                             "format=duration", "-of",
                             "default=noprint_wrappers=1:nokey=1", filename],
        stdout=,
        stderr=)
    return float()
print("minute:"+str(int(get_length("test.mp4")) // 60))
print("second:"+str(int(get_length("test.mp4")) % 60))

Convert video to frame sequence

import cv2
import numpy as np
import os
video = ("test.mp4")
result_path = './save_result' # Saved foldersuccess, frame = ()
i = 0
while success:
    ((result_path,str(i)+'.png'),frame)
    i = i + 1
    success, frame = ()

Extract faces from pictures

from PIL import Image
import face_recognition
inputImg = ""
image = face_recognition.load_image_file(inputImg)
faces = face_recognition.face_locations(image)
for i in range(len(faces)):
    top, right, bottom, left = faces[i]
    faceImage = image[top:bottom, left:right]
    final = (faceImage)
    ("img%" % (str(i)), "PNG")

Merge local a.mp4 and b.mp4 into output.mp4 using ffmpeg >1.1 (lossless merge)

First create a text file and add the following information to the text file:

file 'a.mp4'

file 'b.mp4'

ffmpeg -f concat -i -c copy output.mp4

Video frame to video

ffmpeg -f image2 -i /home/ttwang/images/image% tt.mp4

This is the article about using Python to cut videos according to a certain time (for example: crop every 10 seconds). For more related Python videos, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!