├── LICENSE ├── README.md ├── README_EN.md ├── images ├── cover.jpg ├── example.gif └── stable.png ├── main.py ├── output └── 输出文件在这儿Rendered_files_will_be_shown_here.txt ├── python_rotaeno_stabilizer.py ├── requirements.txt └── videos └── 将录屏放在这里Put_your_recordings_here.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Rotaeno Stabilizer 2 | 3 | *Read this in [English](README_EN.md)* 4 | 5 | ![Python Rotaeno Stabilizer](images/cover.jpg) 6 | 7 | [视频演示](https://www.bilibili.com/video/BV1bc411f7fK/?share_source=copy_web&vd_source=9e94008dbf76e399a164028430118348) 8 | 9 | 这是一个基于Python的Rotaeno录屏稳定脚本,原理和Rotaeno官方提供的Adobe After 10 | Effects脚本一样,是基于直播模式下录屏画面四个角的颜色来旋转帧,从而达到稳定视频画面的目的。 11 | 12 | # 更新记录 13 | 14 | ## v1.3 15 | - 新增背景圆圈, 优化画面观感 16 | - 修复了脚本在Windows上运行的一些bug 17 | - 修复了长宽比偏小的录屏无法正常添加背景圆圈的问题 18 | - 新增了对于mov, avi, mkv, wmv, flv格式的支持 19 | 20 | ## v1.2 21 | 22 | - 增加多进程优化 23 | 24 | ## v1.1 25 | 26 | - 增加正方形渲染功能(感谢[@Ki-wimon](https://github.com/Ki-wimon)的PR),脚本默认采用正方形渲染,以最大程度减少画面裁切 27 | - 为`convert_vfr_to_cfr`和`add_audio_to_video`函数增加了verbose=False形参,减少命令行输出的冗余 28 | - 删除中间文件,仅保留最后输出 29 | 30 | ## v1.0 31 | 32 | - 增加了V2矫正方法,脚本默认按照V2来稳定视频,如果有V1矫正的需要,请在视频文件名前面添加"v1" 33 | 字样,脚本将自动切换到V1矫正模式进行稳定,例如:`v1-sample.mp4`。 34 | 35 | ## 功能特点 36 | 37 | - 无需安装Adobe After Effects,一行命令即可渲染完成 38 | - 支持批量处理视频 39 | 40 | ## 安装 41 | 42 | 1. 下载项目代码: 43 | 44 | ```shell 45 | git clone https://github.com/Lawrenceeeeeeee/python_rotaeno_stabilizer.git 46 | ``` 47 | 48 | 或者直接在本仓库界面点击Download ZIP下载然后解压 49 | 50 | 2. 安装依赖: 51 | 52 | ```shell 53 | # 切换到脚本所在目录 54 | cd python_rotaeno_stabilizer 55 | pip install -r requirements.txt 56 | ``` 57 | 58 | 3. 安装FFmpeg 59 | 60 | 请在[FFmpeg官网](https://ffmpeg.org/download.html)上下载对应的安装包 61 | 62 | ## 使用方法 63 | 64 | 0. **注意!!!** 录屏前请在Rotaeno的设置中开启"直播模式",开启后屏幕的四个角将会出现记录设备旋转角的色块。 65 | 66 | 1. 将待处理的视频放在`videos`目录下 (目前支持mp4, mov, avi, mkv, wmv, flv) 67 | 68 | 2. 启动项目: 69 | 70 | ```shell 71 | python main.py 72 | ``` 73 | 74 | 3. 在`output`文件夹找渲染完成的视频 75 | 76 | 效果如下: 77 | 78 | ![演示](images/example.gif) 79 | 80 | ## 联系作者 81 | 82 | 请在我的[Bilibili账号](https://space.bilibili.com/143784401)下私信我 83 | -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 | # Python Rotaeno Stabilizer (English README) 2 | 3 | *阅读 [中文版](README.md).* 4 | 5 | ![Python Rotaeno Stabilizer](images/cover.jpg) 6 | 7 | Check out 8 | the [video demonstration](https://www.bilibili.com/video/BV1bc411f7fK/?share_source=copy_web&vd_source=9e94008dbf76e399a164028430118348) 9 | 10 | This is a Python-based Rotaeno screen recording stabilization script. Its principle is the same as the script provided 11 | by Rotaeno for Adobe After Effects, which rotates frames based on the colors of the four corners of the screen recording 12 | in live broadcast mode. The goal is to stabilize the video image. 13 | 14 | # Update Log 15 | 16 | ## v1.3 17 | - Added background circle, optimized visual experience 18 | - Fixed some bugs when the script runs on Windows 19 | - Fixed the issue where the background circle could not be properly added to screen recordings with a small width-height ratio. 20 | - Added support for mov, avi, mkv, wmv, flv formats 21 | 22 | ## v1.2 23 | 24 | - Added multi-process optimization. 25 | 26 | ## v1.1 27 | 28 | - Added square rendering feature (thanks to the PR by [@Ki-wimon](https://github.com/Ki-wimon)). The script now defaults 29 | to square rendering to minimize cropping of the frame. 30 | - Added a `verbose=False` parameter to the `convert_vfr_to_cfr` and `add_audio_to_video` functions to reduce redundant 31 | command line output. 32 | - Deleted intermediate files, keeping only the final output. 33 | 34 | ## v1.0 35 | 36 | - Added the V2 correction method. The script now defaults to stabilizing videos using V2. If V1 correction is needed, 37 | please add "v1" at the beginning of the video filename. The script will automatically switch to V1 correction mode for 38 | stabilization, e.g., `v1-sample.mp4`. 39 | 40 | ## Features 41 | 42 | - No need to install Adobe After Effects; rendering can be done with just one command. 43 | - Supports batch processing of videos. 44 | 45 | ## Installation 46 | 47 | 1. Download the project code: 48 | 49 | ```shell 50 | git clone https://github.com/Lawrenceeeeeeee/python_rotaeno_stabilizer.git 51 | ``` 52 | 53 | Alternatively, you can directly click "Download ZIP" on this repository page, then unzip the downloaded file. 54 | 55 | 2. Install the dependencies: 56 | 57 | ```shell 58 | # Navigate to the directory containing the script 59 | cd python_rotaeno_stabilizer 60 | pip install -r requirements.txt 61 | ``` 62 | 63 | 3. Install FFmpeg 64 | 65 | Please download the appropriate installation package from 66 | the [FFmpeg official website](https://ffmpeg.org/download.html). 67 | 68 | ## How to Use 69 | 70 | 0. **Attention!** Before recording, ensure the "Streaming Mode" is activated in Rotaeno settings. Once enabled, the four 71 | corners of the screen will display color blocks, which indicate the device's rotation angle. 72 | 73 | 1. Place the video to be processed in the videos directory (currently supports mp4, mov, avi, mkv, wmv, flv). 74 | 75 | 2. Start the project: 76 | 77 | ```shell 78 | python main.py 79 | ``` 80 | 81 | 3. Once processing is complete, find the rendered videos in the `output` folder. 82 | 83 | 84 | Result as follows: 85 | 86 | ![Demo](images/example.gif) 87 | -------------------------------------------------------------------------------- /images/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lawrenceeeeeeee/python_rotaeno_stabilizer/6e6504f5e3867404c66d94c5752daab5936eedc2/images/cover.jpg -------------------------------------------------------------------------------- /images/example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lawrenceeeeeeee/python_rotaeno_stabilizer/6e6504f5e3867404c66d94c5752daab5936eedc2/images/example.gif -------------------------------------------------------------------------------- /images/stable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lawrenceeeeeeee/python_rotaeno_stabilizer/6e6504f5e3867404c66d94c5752daab5936eedc2/images/stable.png -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import time 4 | 5 | from python_rotaeno_stabilizer import RotaenoStabilizer 6 | 7 | def find_all_videos(): 8 | """ 9 | 寻找videos目录下的所有视频文件,不区分大小写 10 | :return: 视频列表 11 | """ 12 | video_dir = os.path.join(os.getcwd(), 'videos') # 指向videos目录 13 | videos = [] 14 | # 获取所有支持的视频文件扩展名(转换为小写) 15 | video_extensions = [ext.lower() for ext in RotaenoStabilizer.format_to_fourcc.keys()] 16 | 17 | for file_path in glob.glob(os.path.join(video_dir, '*.*')): 18 | if os.path.isfile(file_path): 19 | _, ext = os.path.splitext(file_path) 20 | # 检查文件扩展名是否在支持的列表中 21 | if ext.lower() in video_extensions: 22 | relative_path = os.path.relpath(file_path, video_dir) 23 | videos.append(relative_path) 24 | 25 | return videos 26 | 27 | 28 | 29 | if __name__ == '__main__': 30 | videos = find_all_videos() 31 | print(videos) 32 | for video in videos: 33 | start = time.time() 34 | try: 35 | print("正在处理:", video) 36 | if video[0:2] == "v1": 37 | stab_task = RotaenoStabilizer(video, type="v1") 38 | else: 39 | stab_task = RotaenoStabilizer(video) 40 | 41 | stab_task.run() 42 | except Exception as e: 43 | print("处理视频时发生错误:", e) 44 | end = time.time() 45 | print(f"用时:{end - start}s") 46 | 47 | # if __name__ == '__main__': 48 | # videos = find_all_videos() 49 | # print(videos) 50 | # for video in videos: 51 | # start = time.time() 52 | # print("正在处理:", video) 53 | # if video[0:2] == "v1": 54 | # stab_task = RotaenoStabilizer(video, type="v1") 55 | # else: 56 | # stab_task = RotaenoStabilizer(video) 57 | # 58 | # stab_task.run() 59 | # 60 | # end = time.time() 61 | # print(f"用时:{end - start}s") -------------------------------------------------------------------------------- /output/输出文件在这儿Rendered_files_will_be_shown_here.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lawrenceeeeeeee/python_rotaeno_stabilizer/6e6504f5e3867404c66d94c5752daab5936eedc2/output/输出文件在这儿Rendered_files_will_be_shown_here.txt -------------------------------------------------------------------------------- /python_rotaeno_stabilizer.py: -------------------------------------------------------------------------------- 1 | import math 2 | import multiprocessing as mp 3 | import os 4 | import queue 5 | import subprocess 6 | import time 7 | from functools import wraps 8 | 9 | import cv2 10 | import numpy as np 11 | from tqdm import tqdm 12 | 13 | 14 | def timer(fn): 15 | """计算性能的修饰器""" 16 | 17 | @wraps(fn) 18 | def measure_time(*args, **kwargs): 19 | t1 = time.time() 20 | result = fn(*args, **kwargs) 21 | t2 = time.time() 22 | print(f"@timer: {fn.__name__} took {t2 - t1: .5f} s") 23 | return result 24 | 25 | return measure_time 26 | 27 | 28 | class RotaenoStabilizer: 29 | format_to_fourcc = { 30 | '.mp4': 'mp4v', 31 | '.mov': 'avc1', 32 | '.avi': 'XVID', # 或 'DIVX' 33 | '.mkv': 'H264', 34 | '.wmv': 'WMV1', 35 | '.flv': 'FLV1' 36 | } 37 | 38 | def __init__(self, video, type="v2", square=True): 39 | self.video_file = video 40 | self.type = type 41 | self.square = square 42 | self.video_dir = video if os.path.isabs(video) else os.path.join(os.getcwd(), 'videos', video) # 判断是否为绝对路径 43 | self.video_file_name = os.path.basename(video) # 获取不带路径的文件名 44 | self.video_name = os.path.splitext(self.video_file_name)[0] # 获取文件名 45 | self.video_extension = os.path.splitext(self.video_file_name)[1] # 获取文件后缀 46 | self.output_path = os.path.join(os.getcwd(), 'output', 47 | f'{self.video_name}_stb{self.video_extension}') # 指定输出路径 48 | self.cfr_output_path = os.path.join(os.getcwd(), 'output', 49 | f'{self.video_name}_cfr{self.video_extension}') # 指定输出路径 50 | self.refined_video_path = os.path.join(os.getcwd(), 'output', 51 | f'{self.video_name}_refined{self.video_extension}') 52 | cap = cv2.VideoCapture(self.video_dir) 53 | self.fps = cap.get(cv2.CAP_PROP_FPS) 54 | 55 | if self.video_extension.lower() in self.format_to_fourcc: 56 | self.fourcc = cv2.VideoWriter_fourcc(*self.format_to_fourcc[self.video_extension.lower()]) 57 | else: 58 | raise ValueError(f"Unsupported video format: {self.video_extension}") 59 | # self.fourcc = cv2.VideoWriter_fourcc(*'mp4v') 60 | cap.release() 61 | 62 | self.num_cores = os.cpu_count() if os.cpu_count() < 61 else 61 63 | 64 | @timer 65 | def add_audio_to_video(self, input_video=None, audio=None, verbose=False): 66 | """ 67 | 将音频添加到视频中。 68 | 69 | :param input_video: 输入的视频文件路径。如果为 None,则使用实例的 output_path 属性。 70 | :param audio: 输入的音频来源文件路径。如果为 None,则使用实例的 video_dir 属性。 71 | :param verbose: 是否显示详细的 ffmpeg 输出,默认为 False。 72 | :return: None 73 | """ 74 | if input_video is None: 75 | input_video = self.output_path 76 | if audio is None: 77 | audio = self.video_dir 78 | output_file = f'output/{self.video_name}_with_audio{self.video_extension.lower()}' 79 | command = [ 80 | 'ffmpeg', 81 | '-i', input_video, # 输入的视频文件 82 | '-i', audio, # 输入的音频来源文件 83 | '-c:v', 'copy', # 复制视频流 84 | '-c:a', 'aac', # 使用 AAC 编码音频 85 | '-strict', 'experimental', 86 | output_file # 输出的文件名 87 | ] 88 | 89 | if not verbose: 90 | # 抑制 stdout 和 stderr 输出 91 | with open(os.devnull, 'wb') as devnull: 92 | subprocess.run(command, stdout=devnull, stderr=devnull) 93 | else: 94 | subprocess.run(command) 95 | 96 | @timer 97 | def convert_vfr_to_cfr(self, verbose=False): 98 | """ 99 | 将可变帧率 (VFR) 视频转换为固定帧率 (CFR) 视频。 100 | 101 | :param verbose: 是否显示详细的 ffmpeg 输出,默认为 False。 102 | :return: None 103 | """ 104 | cmd = [ 105 | 'ffmpeg', 106 | '-i', self.video_dir, 107 | '-vf', f'fps={self.fps}', 108 | '-c:a', 'copy', # 复制音频流而不重新编码 109 | self.cfr_output_path 110 | ] 111 | 112 | if not verbose: 113 | # 抑制 stdout 和 stderr 输出 114 | with open(os.devnull, 'wb') as devnull: 115 | subprocess.run(cmd, stdout=devnull, stderr=devnull) 116 | else: 117 | subprocess.run(cmd) 118 | 119 | def get_video_duration(self, video_path): 120 | """ 121 | 122 | :param video_path: 视频路径 123 | :return: 时长 124 | """ 125 | cmd = [ 126 | 'ffprobe', 127 | '-v', 'error', 128 | '-show_entries', 'format=duration', 129 | '-of', 'default=noprint_wrappers=1:nokey=1', 130 | video_path 131 | ] 132 | 133 | result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 134 | return float(result.stdout) 135 | 136 | def compute_rotation(self, left_color, right_color, center_color, sample_color): 137 | """ 138 | 根据画面四个角的颜色来计算画面旋转角度 139 | :param left_color: 140 | :param right_color: 141 | :param center_color: 142 | :param sample_color: 143 | :return: 旋转角度 144 | """ 145 | OffsetDegree = 180.0 146 | 147 | centerDist = np.linalg.norm(np.array(center_color) - np.array(sample_color)) 148 | leftLength = np.linalg.norm(np.array(left_color) - np.array(center_color)) 149 | leftDist = np.linalg.norm(np.array(left_color) - np.array(sample_color)) 150 | rightDist = np.linalg.norm(np.array(right_color) - np.array(sample_color)) 151 | 152 | dir = -1 if leftDist < rightDist else 1 153 | if leftLength == 0: 154 | angle = OffsetDegree # 或其他合适的默认值 155 | else: 156 | angle = (centerDist - leftLength) / leftLength * 180.0 * dir + OffsetDegree 157 | 158 | # 注意,如果旋转方向是相反的,只需返回-angle即可 159 | return -angle 160 | 161 | def compute_rotation_v2(self, top_left_color, top_right_color, bottom_left_color, bottom_right_color): 162 | ''' 163 | 根据画面四个角的颜色来计算画面旋转角度 164 | :param top_left_color: 左上角的颜色 (RGB) 165 | :param top_right_color: 右上角的颜色 (RGB) 166 | :param bottom_left_color: 左下角的颜色 (RGB) 167 | :param bottom_right_color: 右下角的颜色 (RGB) 168 | :return: 旋转角度 169 | ''' 170 | 171 | # 将RGB值转换为0或1 172 | def convert_color_to_binary(color): 173 | array = [1 if c >= 255 / 2 else 0 for c in color] 174 | return array[::-1] # OpenCV的BGR顺序和RGB相反 175 | 176 | # 将四个角的颜色转换为二进制 177 | binary_top_left = convert_color_to_binary(top_left_color) 178 | binary_top_right = convert_color_to_binary(top_right_color) 179 | binary_bottom_left = convert_color_to_binary(bottom_left_color) 180 | binary_bottom_right = convert_color_to_binary(bottom_right_color) 181 | 182 | # 将二进制颜色值转换为角度 183 | color_to_degree = (binary_top_left[0] * 2048 + binary_top_left[1] * 1024 + binary_top_left[2] * 512 + 184 | binary_top_right[0] * 256 + binary_top_right[1] * 128 + binary_top_right[2] * 64 + 185 | binary_bottom_left[0] * 32 + binary_bottom_left[1] * 16 + binary_bottom_left[2] * 8 + 186 | binary_bottom_right[0] * 4 + binary_bottom_right[1] * 2 + binary_bottom_right[2]) 187 | rotation_degree = color_to_degree / 4096 * -360 188 | 189 | return -rotation_degree 190 | 191 | @timer 192 | def improve_video_quality(self, target_bitrate='50M', verbose=False): 193 | """ 194 | 使用FFmpeg提高视频的码率以改善画质。 195 | 196 | 参数: 197 | - target_bitrate: 目标视频码率,例如 '50M' 代表50 Mbps。 198 | - verbose: 是否显示详细的 ffmpeg 输出,默认为 False。 199 | """ 200 | # 构建FFmpeg命令 201 | command = [ 202 | 'ffmpeg', 203 | '-i', self.output_path, # 输入视频文件 204 | '-b:v', target_bitrate, # 设置视频码率 205 | '-c:v', 'libx264', # 设置视频编码器为libx264 206 | '-preset', 'slow', # 使用slow预设,以提高编码效率,但编码速度较慢 207 | self.refined_video_path # 输出视频文件 208 | ] 209 | 210 | # 根据verbose参数设置输出 211 | if verbose: 212 | subprocess.run(command, check=True) 213 | else: 214 | # 抑制 stdout 和 stderr 输出 215 | with open(os.devnull, 'wb') as devnull: 216 | subprocess.run(command, stdout=devnull, stderr=devnull, check=True) 217 | 218 | if verbose: 219 | print(f"视频质量改善完成,输出文件已保存至: {self.refined_video_path}") 220 | 221 | def process_frame(self, frame): 222 | height, width, channels = frame.shape 223 | 224 | # Sample colors 225 | O = 5 226 | S = 3 227 | bottom_left = frame[height - O:height - O + S, O:O + S].mean(axis=(0, 1)) 228 | top_left = frame[O:O + S, O:O + S].mean(axis=(0, 1)) 229 | bottom_right = frame[height - O:height - O + S, width - O:width - O + S].mean(axis=(0, 1)) 230 | top_right = frame[O:O + S, width - O:width - O + S].mean(axis=(0, 1)) 231 | 232 | if self.type == 'v2': 233 | angle = self.compute_rotation_v2(top_left, top_right, bottom_left, bottom_right) 234 | else: 235 | angle = self.compute_rotation(top_left, bottom_right, top_right, bottom_left) 236 | 237 | # Rotate frame 238 | max_size = math.ceil(math.sqrt(width ** 2 + height ** 2)) 239 | if self.square: # 方形渲染 240 | """ 241 | 设手机尺寸为a*b, 长a, 宽b 242 | 判定环内径: (1050**2+888**2)**0.5 1383/888 243 | l = 1.1824324324 * b 244 | ((1.1824324324**2+1)**0.5 * height + 7) 245 | 判定环宽度: 14 (1216宽度下是17) 246 | 247 | 如果录屏的长宽比小于1.7763157895,则将宽度设置成 长度/1.7763157895 248 | """ 249 | # max_size = max(height, width) 250 | background_frame = np.zeros((max_size, max_size, 3), dtype='uint8') 251 | 252 | # 在背景上绘制圆环 253 | real_height = height if width / height >= 1.7763157895 else width / 1.7763157895 254 | circle_center = (max_size // 2, max_size // 2) 255 | circle_radius = (1.5574 * real_height) // 2 256 | circle_thickness = int(3 / 328 * real_height - 46 / 41) # 圆环的宽度,比如15px 257 | cv2.circle(background_frame, circle_center, math.ceil(circle_radius), (255, 255, 255), 258 | thickness=circle_thickness) 259 | 260 | # 将原始视频帧放置在中间 261 | expanded_frame = np.zeros((max_size, max_size, 3), dtype='uint8') 262 | x_offset = (max_size - width) // 2 263 | y_offset = (max_size - height) // 2 264 | expanded_frame[y_offset:y_offset + height, x_offset:x_offset + width] = frame 265 | 266 | # 对扩展帧进行旋转 267 | M = cv2.getRotationMatrix2D((max_size // 2, max_size // 2), angle, 1) 268 | rotated_frame = cv2.warpAffine(expanded_frame, M, (max_size, max_size)) 269 | 270 | # 创建掩码以识别非黑色像素 271 | _, mask = cv2.threshold(cv2.cvtColor(rotated_frame, cv2.COLOR_BGR2GRAY), 1, 255, cv2.THRESH_BINARY) 272 | 273 | # 使用掩码叠加非黑色像素到背景帧 274 | background_frame_masked = cv2.bitwise_and(background_frame, background_frame, mask=cv2.bitwise_not(mask)) 275 | rotated_frame_masked = cv2.bitwise_and(rotated_frame, rotated_frame, mask=mask) 276 | combined_frame = cv2.add(background_frame_masked, rotated_frame_masked) 277 | return combined_frame 278 | else: 279 | M = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1) 280 | rotated_frame = cv2.warpAffine(frame, M, (width, height)) 281 | 282 | return rotated_frame 283 | 284 | def process_video(self, group_number, frame_jump_unit): 285 | cap = cv2.VideoCapture(self.cfr_output_path) 286 | cap.set(cv2.CAP_PROP_POS_FRAMES, frame_jump_unit * group_number) 287 | proc_frames = 0 288 | inter_output_path = os.path.join(os.getcwd(), 'output', 289 | "{}.{}".format(group_number, f'{self.video_extension.lower()[1:]}')) 290 | 291 | frame_size = math.ceil(math.sqrt(int(cap.get(3)) ** 2 + int(cap.get(4)) ** 2)) 292 | if self.square: # 方形 293 | out = cv2.VideoWriter(inter_output_path, self.fourcc, self.fps, (frame_size, frame_size)) 294 | else: 295 | out = cv2.VideoWriter(inter_output_path, self.fourcc, self.fps, (int(cap.get(3)), int(cap.get(4)))) 296 | 297 | while proc_frames < frame_jump_unit: 298 | ret, frame = cap.read() 299 | if ret: 300 | out.write(self.process_frame(frame)) 301 | else: 302 | print("Error reading frame") 303 | proc_frames += 1 304 | 305 | cap.release() 306 | out.release() 307 | return None 308 | 309 | def concatenate_videos(self, verbose=False): 310 | # 构建 FFmpeg 命令 311 | cmd = [ 312 | 'ffmpeg', 313 | '-f', 'concat', 314 | '-safe', '0', # 如果文件名包含特殊字符,需要此选项 315 | '-i', 'output/intermediate_files.txt', 316 | '-c', 'copy', # 使用 'copy' 来避免重新编码 317 | self.output_path 318 | ] 319 | 320 | # 执行命令 321 | if not verbose: 322 | # 抑制 stdout 和 stderr 输出 323 | with open(os.devnull, 'wb') as devnull: 324 | subprocess.run(cmd, stdout=devnull, stderr=devnull) 325 | else: 326 | subprocess.run(cmd) 327 | 328 | @timer 329 | def render(self): 330 | """ 331 | :return: 无返回值: 332 | 在output文件夹中输出渲染完毕的视频 333 | """ 334 | cap2 = cv2.VideoCapture(self.cfr_output_path) 335 | frame_jump_unit = cap2.get(cv2.CAP_PROP_FRAME_COUNT) // self.num_cores # 每个进程处理的帧数 336 | cap2.release() 337 | 338 | p = mp.Pool(self.num_cores) 339 | video_list = range(self.num_cores) 340 | video_list = [(item, frame_jump_unit) for item in video_list] 341 | p.starmap(self.process_video, video_list) # 多进程开始 342 | 343 | intermediate_files = ["{}.{}".format(i, f'{self.video_extension.lower()[1:]}') for i in range(self.num_cores)] 344 | # print(intermediate_files) 345 | 346 | with open("output/intermediate_files.txt", "w") as f: 347 | for t in intermediate_files: 348 | f.write("file {} \n".format(t)) 349 | 350 | self.concatenate_videos() 351 | 352 | # 删除中间文件 353 | for f in intermediate_files: 354 | os.remove(os.path.join(os.getcwd(), 'output', f)) 355 | os.remove("output/intermediate_files.txt") 356 | 357 | def run(self): # 渲染方形视频 358 | """ 359 | :return: 无返回值,在output文件夹输出渲染完毕的视频 360 | """ 361 | 362 | cap = cv2.VideoCapture(self.video_dir) 363 | 364 | print("正在将视频转换为CFR视频……") 365 | self.convert_vfr_to_cfr() 366 | cap.release() 367 | 368 | # 接下来只处理CFR视频 369 | self.render() 370 | # self.improve_video_quality() 371 | self.add_audio_to_video() 372 | 373 | os.remove(self.cfr_output_path) 374 | os.remove(self.output_path) 375 | 376 | print(f"{self.video_file_name}稳定完成") 377 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | mpmath==1.3.0 2 | numpy 3 | opencv-contrib-python==4.8.1.78 4 | opencv-python==4.8.1.78 5 | Pillow==10.0.1 6 | psutil==5.9.6 7 | tqdm==4.66.1 8 | -------------------------------------------------------------------------------- /videos/将录屏放在这里Put_your_recordings_here.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lawrenceeeeeeee/python_rotaeno_stabilizer/6e6504f5e3867404c66d94c5752daab5936eedc2/videos/将录屏放在这里Put_your_recordings_here.txt --------------------------------------------------------------------------------