Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Python Automated short Video Generation script to realize popular Video Pipeline production

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you the content of the example analysis of Python automated short video generation script to achieve popular video pipeline production. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

I. Design of core functions

First of all, I watched the videos of those video marketing accounts on the Internet, most of which revolved around a theme through a few pictures and added some popular songs as background music.

Knowing the general idea, we can implement it through the following steps:

Crawl pictures in batches through keywords

Filter the crawled images and unify the size of the resize in batches

Video synthesis of uniform-sized pictures

Intercept the appropriate background music according to the selected song

Merge video with intercepted background music

Second, realize step 1. Picture crawling

Of course, if your partner already has video material, you can skip to step 4 if you just want to add a background to the video; if you already have image material that doesn't need to be crawled, you can skip to step 2.

In the first step, we can search keyword images according to the desired video theme and crawl the images in batches. For example, we take the Japanese animation "your name" as the theme, by entering keywords, crawl animation-related pictures. The core code is as follows:

Def dowmloadimg (html, keyword, startNum): headers = {'user-agent':' Mozilla/5.0'} # request header pic_url = re.findall ('"objURL": "(. *?)",', html Re.S) # find the regular URL num = len (pic_url) I = startNum subroot = root txtpath = subroot +'/ download_img.txt' print ('find the keyword:' + keyword +' Start downloading pictures.') For each in pic_url: a ='th'+ str (I + 1) + 'picture Image address:'+ str (each) +'\ n'b = 'downloading' + a print (b) path = subroot +'/'+ str (I + 1) try: if not os.path.exists (subroot): os.makedirs (subroot) if not os.path.exists (path): pic = requests.get (each, headers=headers) Timeout=10) with open (path + '.jpg', 'wb') as f: f.write (pic.content) f.close () with open (txtpath) 'a') as f: f.write (a) f.close () except: traceback.print_exc () print The current picture cannot be downloaded!) Continue I + = 1 return iwords = input ("Please enter keywords:") root ='. /'+ wordsif not os.path.exists (root): os.makedirs (root) # Parameter is the number of pages to be crawled for i in range (2): url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + words + "& pn=" + str (pageId) + "& gsm=?&ct=& Ic=0&lm=-1&width=0&height=0 "pageId + = 20 html = requests.get (url Headers=headers) lastNum = dowmloadimg (html.text, words, lastNum,) # execute to get 60 images at a time

At this point, we can climb down the picture according to the keyword and name the picture in numerical order, as shown in the following figure.

two。 Uniform format and size of pictures

In the second step, we need to unify the size and format of the acquired images to facilitate the subsequent video synthesis. Here, we can manually filter some images that need to be uniformly sized by resize, or we can format the images in batches under the crawled folder. The size of the picture can be set by code, here we unify the size of all the pictures into 600 '800. The core code is as follows:

# resize all the images to 600cm 800, and save def resize_image (image_name): # get all the files in the input folder files = os.listdir ('. /'+ image_name) output_dir ='. / resize/' # to determine whether the output folder exists If it does not exist, create if not os.path.exists (output_dir): os.makedirs (output_dir) for file in files: if file [- 4:] = = ".jpg": img = Image.open ('. /'+ image_name +'/'+ file) # convert all images to RGB Prevent abnormal picture format img = img.convert ('RGB') # resize picture size is set to 600' 800 img = img.resize ((600,800), Image.ANTIALIAS) img.save (os.path.join (output_dir, file))

3. Video synthesis

In the third step, we can synthesize these pictures with uniform format and size, here we can synthesize all the pictures in the whole folder, or we can select some of them manually. When composing, we merge according to the numerical naming order of the image. The core code is as follows:

Def charts2video (img_path Video_path): "" convert pictures under a given directory to video img_path: picture path video_path: path name of output video return: video converted from picture "images = os.listdir (img_path) images.sort (key=lambda x: int (x [:-4])) # from small to large with the number of the name string Order fps = 1.5 # frames fourcc = cv2.VideoWriter_fourcc ('D' Im = Image.open (img_path + images [0]) video_writer = cv2.VideoWriter (video_path, fourcc, fps) Im.size) for img_i in images: frame = cv2.imread (img_path + img_i) print ('start adding' + img_i +'to the video\ n') video_writer.write (frame) # the picture size must be the same as the video size Otherwise, it will not be added to the video! Video_writer.release ()

Here, if we want to control the number of pictures played per second, we can set the number of frames according to the number of pictures played per second represented by fps, so as to complete the video synthesis of the images.

4. Intercept background music

Fourth, before intercepting the background music, we first need to confirm the length of the video so that we can intercept the timely background music. So we can get the length of the video first. The length of the video in s is returned. The core code is as follows:

Def get_video_time (filename): cap = cv2.VideoCapture (filename) if cap.isOpened (): rate = cap.get (5) frame_num = cap.get (7) duration = frame_num/rate return duration return-1t = get_video_duration ('. / your name .mp4')

The duration of the video is known, and then we are going to intercept the background music. The blogger has written an article before.

If you are interested in how to make a cool music player with Python, you can take a look at how it is made.

Today we will use this homemade music player to download the music we need. For example, we use "misplaced time and space" as the background music, we can first download this song to the local through this music player. This is shown in the following figure.

Music download is finished, followed by music interception, here we provide two ways. One is to intercept the best part of the song, and the other is to choose the intercept interval of the song.

The best part of the song is automatically intercepted:

For those who often browse short videos, you can see that the background music of many short videos on the Internet is the best part of the song. So can Python automatically get the best part of the song? That's for sure! Python has taken into account that it can automatically intercept the best part of the song, here we need to use the pychorus module, specific this is how to achieve, you can look up information and research on the Internet.

First, we need to install the pychorus module.

Pip install pychorus

After the installation is completed, import the pychorus module and call it with one line of code. The parameter t passed here is the video duration we obtained above, which ensures that the captured background music is the same as the video duration, which is convenient for video and music synthesis.

At the same time, we also need to note that the duration of a song is about 3-4 minutes, so we'd better not pass in more than 1 minute, otherwise the best part may fail to intercept. The core code is as follows:

From pychorus import find_and_output_choruschorus_start_sec = find_and_output_chorus (". / misplaced spacetime-Aichen .mp3", ". / misplaced spacetime _ high.wav", t)

As shown in the figure below, we know that the duration of the video is 26s, and then intercept the background music. The best part of the automatic acquisition starts at 2 minutes and 32 seconds, with a duration of 26s. At this point, we can cut out the best part of the current song and merge the final video and music.

Custom intercept song range:

What if our video is too long to capture the best part of the song? We can define the intercept interval of the song to obtain the background music. The following demonstration shows that the intercept song starts at 20s and ends at 90s. The core code is as follows:

# intercept background music audio_background = mpy.AudioFileClip ('. / misplaced space-time-Aichen .mp3'). Subclip (20,90) audio_background.write_audiofile ('bk.mp3')

5. Video and background music merge

Step 5, we need to merge the video with the background music that has just been intercepted to form a new video. The core code is as follows:

Def add_music (): # read substitution video my_clip = mpy.VideoFileClip ('your name .mp4') # intercept background music audio_background = mpy.AudioFileClip ('misplaced space-time _ high.wav') # insert audio final_clip = my_clip.set_audio (audio_background) # save final video final_clip.write_videofile (' result.mp4')

Thank you for reading! This is the end of the article on "sample Analysis of Python Automated short Video Generation script to achieve popular Video production Line". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report