1. 程式人生 > >Python 帶你一鍵生成朋友圈超火的九宮格短視訊

Python 帶你一鍵生成朋友圈超火的九宮格短視訊

![image](https://upload-images.jianshu.io/upload_images/1466987-562453a123270108?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 1\. 場景 如果你經常刷抖音和微信朋友圈,一定發現了最近九宮格短視訊很火! ​從朋友圈九宮格圖片,到九宮格視訊,相比傳統的圖片視訊,前者似乎更有個性和逼格 ![image](https://upload-images.jianshu.io/upload_images/1466987-2379af9c4f8bfd58?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 除了傳統的剪輯軟體可以實現,是否有其他更加快捷方便的方式?比如:一鍵生成,批量生成? 廢話不多說,本篇文章將大家使用 Python 一鍵生成九宮格短視訊,優雅地幫你在朋友圈裝一次逼! ## 2.準備 在開始實戰之前,使用 pip 安裝 2 個依賴,分別是: 1、視訊處理依賴 moviepy 2、圖片處理依賴 PIL ``` # 安裝兩個依賴 # 視訊處理 pip3 install moviepy # 圖片處理依賴 pip3 install Pillow ``` ## 3.實戰一下 在實戰之前,先準備一段原始視訊素材 下面通過 6 個步驟,將原始視訊轉換為九宮格視訊 1、新建處理資料夾 新建一個臨時資料夾和一個視訊輸出資料夾 ``` def mkdir_folder(file_path): """ 建立一個資料夾,如果不存在就建立;否則不做處理 :param file_path: :return: """ if os.path.exists(file_path): return os.mkdir(file_path) # 新建臨時資料夾和輸出資料夾 mkdir_folder(self.path_temp) mkdir_folder(self.path_output) ``` 2、獲取視訊的音訊檔案及視訊基礎資訊 首先,根據原始視訊,使用 moviepy 構建一個 VideoFileClip 物件,從而獲取到視訊的寬、高、幀率、時長等資訊 ``` self.video_raw_clip = VideoFileClip(file_path) # 寬、高 self.video_width, self.video_height = self.video_raw_clip.w, self.video_raw_clip.h # 幀率 self.fps = self.video_raw_clip.fps # 視訊時長 self.during = self.video_raw_clip.duration ``` 接著,從視訊中提取 BGM 音訊物件,並寫入到檔案中 ``` def get_audio_from_video(video_raw_clip, output_path): """ 從視訊中提取音訊 :param video_raw_clip: 視訊Clip物件 :param output_path: 輸出音訊檔案完整路徑 :return: """ audio = video_raw_clip.audio audio.write_audiofile(output_path) return output_path ``` 3、處理視訊幀 我們使用原始視訊 Clip 物件的 iter_frames() 方法,迴圈獲取所有的視訊幀圖片 需要指出的是,為了保證後面視訊合成的便捷性,這裡對視訊幀的檔名按順序進行命令 ``` i = 1 ​for frame in self.video_raw_clip.iter_frames(): image = Image.fromarray(frame) # 視訊幀圖片儲存的臨時路徑(完整路徑) frame_file_complete_path = self.path_temp + "%04d.jpg" % i i += 1 ``` 視訊每一幀都被裁剪成 9 張圖片,我們可以顯式指定圖片之間的距離,然後計算出新畫布的寬和高,最後繪製一個白底背景的圖片 ``` # 1、剪成9張圖片,計算每張圖片的寬、高 item_width = int(self.video_width / 3) item_height = int(self.video_height / 3) # 2、新的寬、高 item_width_new = self.video_width + self.item_space * 2 item_height_new = self.video_height + self.item_space * 2 # 3、重新建一個畫布背景 new_image = Image.new(image.mode, (item_width_new, item_height_new), color='white') ``` 接著,獲取每一塊區域的座標值,針對橫向、縱向第 2、3 個圖片區域加上間隔偏移,貼上到上面新建的圖片上即可 ``` # 4、裁剪圖片,然後貼上到新的畫布中去 # i:橫向、j:縱向 for i in range(0, 3): for j in range(0, 3): # 裁剪區域 box = (j * item_width, i * item_height, (j + 1) * item_width, (i + 1) * item_height) # 根據區域,裁剪圖片 crop_image = image.crop(box) # 橫向、縱向第2塊和第3塊,要加上偏移距離 x = 0 if j == 0 else (item_width + self.item_space) * j y = 0 if i == 0 else (item_height + self.item_space) * i # 將9張圖片,按照上面計算的座標值,貼上到背景中去 new_image.paste(crop_image, (int(x), int(y))) # 儲存圖片到本地 new_image.save(frame_file_complete_path) ``` 4、一籃子圖片重新合成視訊 把上一步生成的幀圖片,按照原視訊的幀率轉為視訊 需要注意的是,為了保證生成的視訊不會錯亂,最好對幀圖片按照名稱進行一次排序 ``` def pics_to_video(pics_path, output_path, fps): """ 圖片轉為視訊 pics_to_video('./../gif_temp/', './../video_temp/temp1.mp4', 20) :param pics_path: :param output_path: :return: """ image_paths = list(map(lambda x: pics_path + x, os.listdir(pics_path))) # 注意:這裡必須進行一次排序,保證所有幀的順序是一致 image_paths = sort_strings_with_emb_numbers(image_paths) # 過濾掉非圖片 image_paths = list(filter(lambda image_path: image_path.endswith('.jpg'), image_paths)) # 圖片剪輯類 clip = ImageSequenceClip(image_paths, fps=fps) clip.write_videofile(output_path) ``` 5、加入 BGM 背景音樂 將原始視訊的音訊檔案設定到上一步生成的視訊檔案,然後寫入一個新的檔案中去 ``` def video_with_audio(path_video_raw, path_bgm_raw, output): """ 視訊合成音訊 :return: """ videoclip = VideoFileClip(path_video_raw) audioclip = AudioFileClip(path_bgm_raw) # 設定視訊音訊,並寫入到檔案中去 videoclip.set_audio(audioclip).write_videofile(output, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True ) ``` 6、刪除臨時檔案 利用 shutil將上面視訊處理的臨時檔案,包含幀圖片、臨時視訊檔案刪除掉 ``` def remove_folder(file_path): """ 刪除資料夾 :param file_path: :return: """ shutil.rmtree(file_path) # 刪除臨時檔案 remove_folder(self.path_temp) ``` ## 4.最後 通過上面的一系列操作,我們實現了將一段視訊處理成九宮格視訊 我已經將文中全部原始碼,包含:生成九宮格視訊和圖片兩套程式碼 上傳到後臺,關注公眾號「**AirPython** 」後回覆「**九宮格** 」即可獲得全部原始碼 如果你覺得文章還不錯,請大家 **點贊、分享、留言**下,因為這將是我持續輸出更多優質文章的最強動力! **推薦閱讀** [帶你用 Python 實現自動化群控(入門篇)](http://mp.weixin.qq.com/s?__biz=MzU1OTI0NjI1NQ==&mid=2247486180&idx=1&sn=7a1d282e608ec14c655e8105984639f7&chksm=fc1b7424cb6cfd3207004c88cd8820a2d7f0b1ad31ba24ab7952a2d66810460bfddc6cd4bc18&scene=21#wechat_redirect) [這些自動化場景,批處理完全可以取代 Python](http://mp.weixin.qq.com/s?__biz=MzU1OTI0NjI1NQ==&mid=2247486072&idx=1&sn=e45a83d7d467d6b3ab8972b43d3c1419&chksm=fc1b74b8cb6cfdae4b385f2a5986fdec56b819e4f1656b4c37f9df1b4bd90c6d3c340e9edf7b&scene=21#wechat_redirect) [我用幾行 Python 自動化指令碼完美解決掉了小姐姐的微信焦慮感](http://mp.weixin.qq.com/s?__biz=MzU1OTI0NjI1NQ==&mid=2247486280&idx=1&sn=0de84df032b528dc04bc6f6a66204096&chksm=fc1b7588cb6cfc9e6c5f458da302f71dbf6aba5badbd70c8f4b63139fe7221f6ddf914c0ba1a&scene=21#wechat_re