Welcome to pay attention
Python wechat ordering applet course video
https://edu.csdn.net/course/detail/36074
Python practical quantitative transaction financial management system
https://edu.csdn.net/course/detail/35475
1. Target scenario
Tiktok or Kwai Fu, and so on, once a video is on fire, many UP owners will scramble to imitate or shoot or edit, then upload to the platform, which will bring good traffic in the end.
For general short videos, you can quickly create a new video through a series of operations such as clipping, special effects transition, adding mixed layers and subtitles. These operations can be realized by Python.
The purpose of this article is to take you to use Python to realize the secondary creation of short video.
2 write code
To realize the secondary creation of short video, the following 7 steps are generally required: obtaining the original video attribute data, video frame processing, video region clipping, making background picture video, synthesizing multiple videos, generating description subtitles, adding subtitles and background music.
Step 1: obtain the original video attribute data
First, using the crawler to obtain the original video without watermark, Github has many ready-made wheels.
Then, instantiate the video clip VideoFileClip to obtain the basic attributes of the video, such as width, height, frame rate and so on.
self.video_raw_clip = VideoFileClip(self.video_raw_path) # Video width and height self.video_width, self.video_height = self.video_raw_clip.w, self.video_raw_clip.h self.fps = self.video_raw_clip.fps
Then, separate the audio file, clip the original video, remove the public picture clips added by the video platform, and regenerate a video file. For example, tiktok will append 4s public video.
# Separate audio self.audio = self.video_raw_clip.audio.subclip(0, self.video_raw_clip.duration - 4) # Clip tail video material temp_video_clip = self.video_raw_clip.subclip(0, self.video_raw_clip.duration - 4) # Generate a new video and save it locally temp_video_clip.set_audio(self.audio) video_path = './source/temp_source_video.mp4' temp_video_clip.write_videofile(video_path, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True)
Step 2: video frame processing
To clip a video, first know the starting coordinate point and clipping range.
Use the ffmpeg command to get the picture frame at a certain time point of the video, and save the picture file locally.
def time_to_hms(seconds_time): """ Time turns to minutes and seconds :param seconds_time: Seconds :return: """ m, s = divmod(seconds_time, 60) h, m = divmod(m, 60) return "%02d:%02d:%02d" % (h, m, s) def get_frame_from_video(video_name, frame_time, img_path): """ Get the frame picture of the video at a certain time and save it locally get_frame_from_video('./../source/source.mp4', 1, './22.jpg') :param video_name: Video path :param frame_time: Time position of intercepted frame(s) :param img_path:Generate the full path of the picture :return: """ # Second to hour, minute, second time_pre = time_to_hms(frame_time) os.system('ffmpeg -ss %s -i %s -frames:v 1 %s' % (time_pre, video_name, img_path))
Then use the ruler and selection tool of PS to cooperate with the information dialog box to obtain the starting coordinates and cutting width and height data to be cut.
# Clipping start coordinates position1 = (0, 328) # 630 is the height to be cropped position2 = (self.video_width, 630)
Step 3: video region clipping
The clip () method provided by moviepy can easily cut the video area.
It should be noted that the coordinate value passed in by the crop() method must be an even number, otherwise region clipping will fail.
def video_crop(self, position1, position2, croped_video_path): """ Video clipping :return: """ # The coordinates of clipping, including the x-axis and Y-axis of the upper left corner; X-axis and y-axis in the lower right corner clip2 = fx.all.crop(self.video_clip, x1=position1[0], y1=position1[1], x2=position2[0], y2=position2[1]) # Save file clip2.write_videofile(croped_video_path) # duration self.time = clip2.duration return clip2
Step 4: make background pictures and videos
In order to ensure the appearance on the mobile phone, you need to mix and add a vertical screen background picture layer or video.
I wrote an article before Making GIF video with pictures The implementation method here is similar, that is, a picture frame is written to the video file circularly.
def one_pic_to_video(image_path, output_video_path, fps, time): """ A picture composite video one_pic_to_video('./../source/1.jpeg', './../source/output.mp4', 25, 10) :param path: Picture file path :param output_video_path:Path to composite video :param fps:Frame rate :param time:duration :return: """ image_clip = ImageClip(image_path) img_width, img_height = image_clip.w, image_clip.h # Total frames frame_num = (int)(fps * time) img_size = (int(img_width), int(img_height)) fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') video = cv2.VideoWriter(output_video_path, fourcc, fps, img_size) for index in range(frame_num): frame = cv2.imread(image_path) # Zoom directly to the specified size frame_suitable = cv2.resize(frame, (img_size[0], img_size[1]), interpolation=cv2.INTER_CUBIC) # Write the picture into the video # How many repeated writes video.write(frame_suitable) # Release resources video.release() return VideoFileClip(output_video_path)
It should be noted that the frame rate and duration of the composite picture video should be consistent with the previous video.
Step 5, synthesize two videos
The above two steps have completed the region clipping of the original video and the production of the background video. Now the two videos can be synthesized at one time.
Because the width of the two videos is likely to be different, in order to ensure the unity of the synthetic video, the length and width of one video need to be scaled in equal proportion to ensure the consistency of the width of the two videos.
def synthetic_video(video1_clip, video2_clip2): """ Synthesize two videos, and the width and height of the generated video shall be subject to the first video :param video1_clip: :param video2_clip2: :return: """ # Finally, the width and height of the video are generated width, height = video1_clip.w, video1_clip.h # Actual width and height of the second video video_width, video_height = video2_clip2.w, video2_clip2.h # Zoom the second video video_clip1 = video2_clip2.resize((width, width * video_height / video_width)) # Path to composite video synthetic_video_clip = CompositeVideoClip([video1_clip, video_clip1.set_pos("center")]) synthetic_video_clip.write_videofile( './source/temp_synthetic_video.mp4') return synthetic_video_clip
Step 6: generate caption
A description information can be generated by TextClip. The text information attributes including font name, size, color, position, start time and duration can be set together.
# Caption description TextClip(text_content, font='./fonts/STHeiti Medium.ttc', fontsize=font_params.get('size'), kerning=font_params.get('kerning'), color=font_params.get('color')).set_position(("center", 150)).set_duration(duration)
The default font may cause Chinese subtitles not to be displayed, so it is best to specify a specific Chinese font.
Step 7, add subtitles and background music
Using CompositeVideoClip, you can embed caption clips into video clips, and then use set_audio adds an audio track to the audio file for the video.
Finally, write to the file, that is, a new short video can be generated.
# Add subtitles video_with_text_clip = CompositeVideoClip([synthetic_video_clip, desc_text_clip.set_start(0)]) # Set background music video_with_text_clip.set_audio(self.audio).write_videofile("output.mp4", codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True ) # Delete all temporary files del_temp_file("./source/")
3 results and conclusions
Through the above 7 steps, you can complete the secondary creation of most short videos.
Full script Download: