diff --git a/Makittalk/.dockerignore b/Makittalk/.dockerignore new file mode 100644 index 00000000..ac4b8399 --- /dev/null +++ b/Makittalk/.dockerignore @@ -0,0 +1,19 @@ +# 忽略以下文件和目录 +.DS_Store +.git +__pycache__ +*.pyc +*.pyo +*.pyd +.idea +.vscode +*.ipynb_checkpoints +*.bzip2 +*.key +*.mp4 +*.wav +*.zip +*.pickle +train/ +data/ +examples/ \ No newline at end of file diff --git a/Makittalk/.gitignore b/Makittalk/.gitignore new file mode 100644 index 00000000..9136d302 --- /dev/null +++ b/Makittalk/.gitignore @@ -0,0 +1,15 @@ +# Ignore large files +*.mp4 +*.dat +*.pth +*.pickle +*.wav +*.bz2 +*.npy + +# Ignore data directories +data/ +examples/ckpt/ +examples/dump/ +train/ +xunlian/ diff --git a/Makittalk/CODE_OF_CONDUCT.md b/Makittalk/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..549b492a --- /dev/null +++ b/Makittalk/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Adobe Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language. +* Being respectful of differing viewpoints and experiences. +* Gracefully accepting constructive criticism. +* Focusing on what is best for the community. +* Showing empathy towards other community members. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances. +* Trolling, insulting/derogatory comments, and personal or political attacks. +* Public or private harassment. +* Publishing others' private information, such as a physical or electronic + address, without explicit permission. +* Other conduct which could reasonably be considered inappropriate in a + professional setting. + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at Grp-opensourceoffice@adobe.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at [https://contributor-covenant.org/version/1/4][version]. + +[homepage]: https://contributor-covenant.org +[version]: https://contributor-covenant.org/version/1/4/ \ No newline at end of file diff --git a/Makittalk/CONTRIBUTING.md b/Makittalk/CONTRIBUTING.md new file mode 100644 index 00000000..3ac4131d --- /dev/null +++ b/Makittalk/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing + +Thanks for choosing to contribute! + +The following are a set of guidelines to follow when contributing to this project. + +## Code Of Conduct + +This project adheres to the Adobe [code of conduct](../CODE_OF_CONDUCT.md). By participating, +you are expected to uphold this code. Please report unacceptable behavior to +[Grp-opensourceoffice@adobe.com](mailto:Grp-opensourceoffice@adobe.com). + +## Have A Question? + +Start by filing an issue. The existing committers on this project work to reach +consensus around project direction and issue solutions within issue threads +(when appropriate). + +## Contributor License Agreement + +All third-party contributions to this project must be accompanied by a signed contributor +license agreement. This gives Adobe permission to redistribute your contributions +as part of the project. [Sign our CLA](https://opensource.adobe.com/cla.html). You +only need to submit an Adobe CLA one time, so if you have submitted one previously, +you are good to go! + +## Code Reviews + +All submissions should come in the form of pull requests and need to be reviewed +by project committers. Read [GitHub's pull request documentation](https://help.github.com/articles/about-pull-requests/) +for more information on sending pull requests. + +Lastly, please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when +submitting a pull request! + +## From Contributor To Committer + +We love contributions from our community! If you'd like to go a step beyond contributor +and become a committer with full write access and a say in the project, you must +be invited to the project. The existing committers employ an internal nomination +process that must reach lazy consensus (silence is approval) before invitations +are issued. If you feel you are qualified and want to get more deeply involved, +feel free to reach out to existing committers to have a conversation about that. + +## Security Issues + +Security issues shouldn't be reported on this issue tracker. Instead, [file an issue to our security experts](https://helpx.adobe.com/security/alertus.html). \ No newline at end of file diff --git a/Makittalk/Dockerfile b/Makittalk/Dockerfile new file mode 100644 index 00000000..68e4d0db --- /dev/null +++ b/Makittalk/Dockerfile @@ -0,0 +1,33 @@ +# 使用Python 3.8官方镜像 +FROM python:3.8-slim-buster + +# 设置工作目录 +WORKDIR /app + +# 安装系统依赖 +# 这些是MakeItTalk项目运行所需的基本依赖 +RUN apt-get update && apt-get install -y \ + build-essential \ + ffmpeg \ + libsm6 \ + libxext6 \ + && rm -rf /var/lib/apt/lists/* + +# 复制requirements文件并安装Python依赖 +# 这样可以利用Docker的缓存机制,提高构建效率 +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# 仅复制必要的代码文件 +COPY *.py . +COPY src/ src/ +COPY util/ util/ +COPY thirdparty/ thirdparty/ + +# 设置环境变量 +# 确保Python输出不被缓冲,方便查看实时日志 +ENV PYTHONUNBUFFERED=1 + +# 设置默认运行命令 +# 可以根据需要修改为其他入口文件 +CMD ["python", "main_end2end.py"] diff --git a/Makittalk/LICENSE.md b/Makittalk/LICENSE.md new file mode 100644 index 00000000..49035ff1 --- /dev/null +++ b/Makittalk/LICENSE.md @@ -0,0 +1,159 @@ +# Creative Commons Attribution-NonCommercial 4.0 International + +Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +### Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). + +* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). + +## Creative Commons Attribution-NonCommercial 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +### Section 1 – Definitions. + +a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + +b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + +c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + +e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + +f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + +g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + +h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. + +i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. + +j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + +k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + +l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning. + +### Section 2 – Scope. + +a. ___License grant.___ + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and + + B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. + + 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. __Term.__ The term of this Public License is specified in Section 6(a). + + 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. __Downstream recipients.__ + + A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. ___Other rights.___ + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. + +### Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +a. ___Attribution.___ + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +### Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; + +b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + +c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +### Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ + +b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ + +c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +### Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +### Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +### Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + +c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. +> +> Creative Commons may be contacted at creativecommons.org diff --git a/Makittalk/PULL_REQUEST_TEMPLATE.md b/Makittalk/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..77ac3297 --- /dev/null +++ b/Makittalk/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,45 @@ + + +## Description + + + +## Related Issue + + + + + + +## Motivation and Context + + + +## How Has This Been Tested? + + + + + +## Screenshots (if appropriate): + +## Types of changes + + + +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to change) + +## Checklist: + + + + +- [ ] I have signed the [Adobe Open Source CLA](https://opensource.adobe.com/cla.html). +- [ ] My code follows the code style of this project. +- [ ] My change requires a change to the documentation. +- [ ] I have updated the documentation accordingly. +- [ ] I have read the **CONTRIBUTING** document. +- [ ] I have added tests to cover my changes. +- [ ] All new and existing tests passed. \ No newline at end of file diff --git a/Makittalk/README.md b/Makittalk/README.md new file mode 100644 index 00000000..f8837ce6 --- /dev/null +++ b/Makittalk/README.md @@ -0,0 +1,115 @@ +# MakeItTalk - 语音驱动面部动画生成 + +组长:王硕,组员:杨勇、付博文、葛钧满 + +项目修改完善主要贡献者:杨勇 + + + +在项目前先讲讲我的一些感受,这个项目我基本上是全程参与,每个部分我都在做,我也不知道我的组员和队长到底做了啥,其实真的很崩溃因为一个人第一次做项目,还有或多或少的问题,为了这个项目不知道熬了多少个夜晚,但是因为个人能力的确有效,也是第一次做这种项目,也很多不懂的地方,最后做的也不是很好,希望大家体谅。 + +也非常感谢这次机会,其实让我学习到了很多很多,从最开始的什么都不会,到后续自己搭建云服务器,处理里面的各种问题,学语音识别相关的知识,看论文,学git,学docker等等,无论怎样,这都是非常棒的一次学习经历。 --杨勇 + +//docker最后精力实在不够了,没有做好,非常抱歉。 + +**MakeItTalk 是一个基于语音输入生成面部动画的开源项目。它可以将单张人像照片与语音结合,生成逼真的说话动画。** + +## 快速开始 + +### 环境准备 +1. 安装Python 3.8环境: +```bash +conda create -n makeittalk_env python=3.8 +conda activate makeittalk_env +``` + +2. 安装依赖:(pynormalize库现在只能从GitHub上找原库拷贝过来) +```bash +pip install -r requirements.txt +git clone https://github.com/giannisterzopoulos/pynormalize.git +cd pynormalize +pip install . +``` + +3. 安装FFmpeg: +```bash +sudo apt-get install ffmpeg +``` + +4. 安装winehq-stable:这个是用来生成卡通人物的,目前测试可以在ubuntu 18.04上完成,注意不同的ubuntu版本需要下载不同的wine。 +sudo dpkg --add-architecture i386 +wget -nc https://dl.winehq.org/wine-builds/winehq.key +sudo apt-key add winehq.key +sudo apt-add-repository 'deb https://dl.winehq.org/wine-builds/ubuntu/ bionic main' +sudo apt update +sudo apt install --install-recommends winehq-stable + +### 运行示例 +1. 准备256x256的人像图片(jpg格式)和语音文件(wav格式),放入文件夹中。 + +2. 运行以下命令生成动画: +```bash +python main_end2end.py --jpg "the way to your portrait.jpg" --wav "the way to your audio.wav" +``` + +3. 生成的动画将保存为`portrait_pred_fls_audio_audio_embed.mp4`(这里portrait是图片的名字,第一个audio是原语音文件的名字) + +### 视频处理 +除此之外,我还编写了process_video.py来进行对视频文件的提取, +该文件会从视频中提取音频,还会截取视频第100帧并裁剪为256x256的肖像图片并保存。 +运行命令如下: +```bash +python process_video.py --video 视频路径 --jpg_output 输出图片路径 --wav_output 输出音频路径 +``` + +示例如下 +```bash +python process_video.py --video evaluate/data/raw/videos/Obama.mp4 --jpg_output examples/Obama.jpg --wav_output examples/Obama.wav +``` +该命令会: + 1.从视频中提取音频并保存为 examples/Obama.wav + 2.截取视频第100帧并裁剪为256x256的肖像图片,保存为 examples/Obama.jpg + +### 模型评估 +这里我们采用了PSNR、SSIM、LPIPS的标准来进行评估。 +评估函数为evaluate_metrics.py +这里我就没用命令行模式来搞了,因为也只有我会来测试,就直接在代码里修改。 +只需要在其124行到127行去配置评估文件路径即可。源码贴在下面 + +```python +real_video = "evaluate/data/raw/videos/Shaheen.mp4" +generated_video = "examples/Shaheen_pred_fls_Shaheen_audio_embed.mp4" +audio_file = "examples/Shaheen.wav" +``` +每次评估的时候自助修改下就好。 + +## 详细使用说明 + +### 参数说明 +- `--jpg`: 输入人像图片路径,我们这里工作目录是最开始的Makeittalk的大文件夹,可以使用绝对路径,也可以使用相对路径。 +- `--wav`: 输入语音文件路径 +- `--amp_lip_x`: 嘴唇水平运动幅度(默认2.0) +- `--amp_lip_y`: 嘴唇垂直运动幅度(默认2.0) +- `--amp_pos`: 头部运动幅度(默认0.5) + +### 示例 +```bash +# 生成更夸张的动画效果 +python main_end2end.py --jpg examples/Obama.jpg --wav examples/Obama.wav --amp_lip_x 3.0 --amp_lip_y 3.0 --amp_pos 1.0 +``` + +## 常见问题 + +### Q: 生成的动画不自然怎么办? +A: 尝试调整`--amp_lip_x`和`--amp_lip_y`参数,找到最适合的幅度值 + +### Q: 如何生成卡通人物动画? +A: 使用`main_end2end_cartoon.py`脚本,并准备透明背景的卡通图片 + +非常抱歉,其实还有好多一些问题,但是都没有记录下来,做项目的经验太少了 +如果遇到了问题,可以联系我的邮箱:3011689827@qq.com + +然后其实做了很多的一些尝试等等,但到写的时候却都忘了,真的做了很多努力,无愧我心。 + +## 许可证 +本项目采用 [MIT License](LICENSE.md) diff --git a/Makittalk/evaluate_metrics.py b/Makittalk/evaluate_metrics.py new file mode 100644 index 00000000..534a9237 --- /dev/null +++ b/Makittalk/evaluate_metrics.py @@ -0,0 +1,135 @@ +import cv2 +import numpy as np +from skimage.metrics import structural_similarity as ssim +from skimage.metrics import peak_signal_noise_ratio as psnr +from torch_fidelity import calculate_metrics +from lpips import LPIPS +import os + +def calculate_psnr(real, generated): + """计算峰值信噪比(PSNR)""" + return psnr(real, generated) + +def calculate_ssim(real, generated): + """计算结构相似性(SSIM)""" + return ssim(real, generated, multichannel=True) + +def calculate_fid(real_dir, generated_dir): + """计算Fréchet Inception Distance(FID)""" + metrics_dict = calculate_metrics( + input1=real_dir, + input2=generated_dir, + cuda=True, + isc=False, + fid=True, + kid=False, + prc=False, + verbose=False + ) + return metrics_dict['frechet_inception_distance'] + +# 全局 LPIPS 模型实例 +_lpips_model = None + +def calculate_lpips(real, generated): + """计算感知相似性(LPIPS)""" + global _lpips_model + import torch + from torchvision import transforms + + # 初始化 LPIPS 模型(仅一次) + if _lpips_model is None: + print("Initializing LPIPS model...") + try: + _lpips_model = LPIPS(net='alex', verbose=False) + print("LPIPS model successfully initialized") + except Exception as e: + print(f"Failed to initialize LPIPS model: {str(e)}") + return float('nan') + + # 将 numpy 数组转换为 PyTorch 张量 + transform = transforms.ToTensor() + try: + real_tensor = transform(real).unsqueeze(0) + gen_tensor = transform(generated).unsqueeze(0) + return _lpips_model(real_tensor, gen_tensor).item() + except Exception as e: + print(f"Error calculating LPIPS: {str(e)}") + return float('nan') + +def evaluate_video_pair(real_video, generated_video, audio_file): + """评估视频对""" + # 视频帧提取和评估 + print(f"Opening real video: {real_video}") + cap_real = cv2.VideoCapture(real_video) + if not cap_real.isOpened(): + raise FileNotFoundError(f"无法打开真实视频文件: {real_video}") + + print(f"Opening generated video: {generated_video}") + cap_gen = cv2.VideoCapture(generated_video) + if not cap_gen.isOpened(): + raise FileNotFoundError(f"无法打开生成视频文件: {generated_video}") + + # 获取视频信息 + print(f"Real video info: {cap_real.get(cv2.CAP_PROP_FRAME_WIDTH)}x{cap_real.get(cv2.CAP_PROP_FRAME_HEIGHT)}") + print(f"Generated video info: {cap_gen.get(cv2.CAP_PROP_FRAME_WIDTH)}x{cap_gen.get(cv2.CAP_PROP_FRAME_HEIGHT)}") + + # 初始化评估结果 + results = { + 'psnr': [], + 'ssim': [], + 'lpips': [] + } + + while True: + ret_real, frame_real = cap_real.read() + ret_gen, frame_gen = cap_gen.read() + + if not ret_real or not ret_gen: + print(f"Processed {len(results['psnr'])} frames") + break + + # 提取生成视频的中间部分(最终生成视频) + h, w = frame_gen.shape[:2] + # 假设中间部分占1/3宽度,位于中间位置 + start = w // 3 + end = 2 * w // 3 + frame_gen = frame_gen[:, start:end, :] # 取中间1/3部分 + + # 调整生成视频帧尺寸以匹配真实视频 + frame_gen = cv2.resize(frame_gen, (frame_real.shape[1], frame_real.shape[0])) + + # 转换为灰度图像 + gray_real = cv2.cvtColor(frame_real, cv2.COLOR_BGR2GRAY) + gray_gen = cv2.cvtColor(frame_gen, cv2.COLOR_BGR2GRAY) + + # 每10帧打印一次进度 + if len(results['psnr']) % 10 == 0: + print(f"Processing frame {len(results['psnr'])} - Adjusted size: {frame_real.shape} -> {frame_gen.shape}") + + # 计算各项指标 + results['psnr'].append(calculate_psnr(gray_real, gray_gen)) + results['ssim'].append(calculate_ssim(gray_real, gray_gen)) + results['lpips'].append(calculate_lpips(frame_real, frame_gen)) + + # 计算平均值 + final_results = {k: np.mean(v) for k, v in results.items()} + + # TODO: 添加LSE-C和LSE-D计算 + # 需要音频和视频的唇部运动分析 + + return final_results + +if __name__ == "__main__": + # 配置评估文件路径 + real_video = "evaluate/data/raw/videos/Shaheen.mp4" + generated_video = "examples/Shaheen_pred_fls_Shaheen_audio_embed.mp4" + audio_file = "examples/Shaheen.wav" + + # 运行评估 + results = evaluate_video_pair(real_video, generated_video, audio_file) + + # 输出结果 + print("Evaluation Results:") + for metric, value in results.items(): + print(f"{metric.upper()}: {value:.4f}") \ No newline at end of file diff --git a/Makittalk/main_end2end.py b/Makittalk/main_end2end.py new file mode 100644 index 00000000..66de4ac8 --- /dev/null +++ b/Makittalk/main_end2end.py @@ -0,0 +1,167 @@ +import sys +sys.path.append('thirdparty/AdaptiveWingLoss') +import os, glob +import numpy as np +import cv2 +import argparse +from src.approaches.train_image_translation import Image_translation_block +import torch +import pickle +import face_alignment +from src.autovc.AutoVC_mel_Convertor_retrain_version import AutoVC_mel_Convertor +import shutil +import util.utils as util +from scipy.signal import savgol_filter + +from src.approaches.train_audio2landmark import Audio2landmark_model + +default_head_name = 'dali' +ADD_NAIVE_EYE = True +CLOSE_INPUT_FACE_MOUTH = False + +parser = argparse.ArgumentParser() +parser.add_argument('--jpg', type=str, required=True, help='Path to input jpg image') +parser.add_argument('--wav', type=str, required=True, help='Path to input wav audio file') +parser.add_argument('--close_input_face_mouth', default=CLOSE_INPUT_FACE_MOUTH, action='store_true') + +parser.add_argument('--load_AUTOVC_name', type=str, default='examples/ckpt/ckpt_autovc.pth') +parser.add_argument('--load_a2l_G_name', type=str, default='examples/ckpt/ckpt_speaker_branch.pth') +parser.add_argument('--load_a2l_C_name', type=str, default='examples/ckpt/ckpt_content_branch.pth') +parser.add_argument('--load_G_name', type=str, default='examples/ckpt/ckpt_116_i2i_comb.pth') + +parser.add_argument('--amp_lip_x', type=float, default=2.) +parser.add_argument('--amp_lip_y', type=float, default=2.) +parser.add_argument('--amp_pos', type=float, default=.5) +parser.add_argument('--reuse_train_emb_list', type=str, nargs='+', default=[]) +parser.add_argument('--add_audio_in', default=False, action='store_true') +parser.add_argument('--comb_fan_awing', default=False, action='store_true') +parser.add_argument('--output_folder', type=str, default='examples') + +parser.add_argument('--test_end2end', default=True, action='store_true') +parser.add_argument('--dump_dir', type=str, default='', help='') +parser.add_argument('--pos_dim', default=7, type=int) +parser.add_argument('--use_prior_net', default=True, action='store_true') +parser.add_argument('--transformer_d_model', default=32, type=int) +parser.add_argument('--transformer_N', default=2, type=int) +parser.add_argument('--transformer_heads', default=2, type=int) +parser.add_argument('--spk_emb_enc_size', default=16, type=int) +parser.add_argument('--init_content_encoder', type=str, default='') +parser.add_argument('--lr', type=float, default=1e-3, help='learning rate') +parser.add_argument('--reg_lr', type=float, default=1e-6, help='weight decay') +parser.add_argument('--write', default=False, action='store_true') +parser.add_argument('--segment_batch_size', type=int, default=1, help='batch size') +parser.add_argument('--emb_coef', default=3.0, type=float) +parser.add_argument('--lambda_laplacian_smooth_loss', default=1.0, type=float) +parser.add_argument('--use_11spk_only', default=False, action='store_true') + +opt_parser = parser.parse_args() + +print(list(face_alignment.LandmarksType)) + +''' STEP 1: preprocess input single image ''' +image_path = opt_parser.jpg +if not os.path.exists(image_path): + print(f"Error: Image file {image_path} not found.") + exit(-1) +img = cv2.imread(image_path) +if img is None: + print(f"Error: Unable to load image from {image_path}.") + exit(-1) +else: + print(f"Image loaded successfully from {image_path}.") + +predictor = face_alignment.FaceAlignment(face_alignment.LandmarksType.THREE_D, device='cuda', flip_input=True) +shapes = predictor.get_landmarks_from_image(img) +if (not shapes or len(shapes) != 1): + print('Cannot detect face landmarks. Exit.') + exit(-1) +shape_3d = shapes[0] + +if opt_parser.close_input_face_mouth: + util.close_input_face_mouth(shape_3d) + +''' Additional manual adjustment to input face landmarks (slimmer lips and wider eyes) ''' +shape_3d[49:54, 1] += 1. +shape_3d[55:60, 1] -= 1. +shape_3d[[37, 38, 43, 44], 1] -= 2 +shape_3d[[40, 41, 46, 47], 1] += 2 + +''' STEP 2: normalize face as input to audio branch ''' +shape_3d, scale, shift = util.norm_input_face(shape_3d) + +''' STEP 3: Generate audio data as input to audio branch ''' +# audio real data +au_data = [] +au_emb = [] +ains = [opt_parser.wav] +for ain in ains: + # 生成音频嵌入 + from thirdparty.resemblyer_util.speaker_emb import get_spk_emb + me, ae = get_spk_emb(ain) + au_emb.append(me.reshape(-1)) + + print('Processing audio file', ain) + c = AutoVC_mel_Convertor('examples') + + au_data_i = c.convert_single_wav_to_autovc_input(audio_filename=ain, autovc_model_path=opt_parser.load_AUTOVC_name) + au_data += au_data_i + +# landmark fake placeholder +fl_data = [] +rot_tran, rot_quat, anchor_t_shape = [], [], [] +for au, info in au_data: + au_length = au.shape[0] + fl = np.zeros(shape=(au_length, 68 * 3)) + fl_data.append((fl, info)) + rot_tran.append(np.zeros(shape=(au_length, 3, 4))) + rot_quat.append(np.zeros(shape=(au_length, 4))) + anchor_t_shape.append(np.zeros(shape=(au_length, 68 * 3))) + +if os.path.exists(os.path.join('examples', 'dump', 'random_val_fl.pickle')): + os.remove(os.path.join('examples', 'dump', 'random_val_fl.pickle')) +if os.path.exists(os.path.join('examples', 'dump', 'random_val_fl_interp.pickle')): + os.remove(os.path.join('examples', 'dump', 'random_val_fl_interp.pickle')) +if os.path.exists(os.path.join('examples', 'dump', 'random_val_au.pickle')): + os.remove(os.path.join('examples', 'dump', 'random_val_au.pickle')) +if os.path.exists(os.path.join('examples', 'dump', 'random_val_gaze.pickle')): + os.remove(os.path.join('examples', 'dump', 'random_val_gaze.pickle')) + +with open(os.path.join('examples', 'dump', 'random_val_fl.pickle'), 'wb') as fp: + pickle.dump(fl_data, fp) +with open(os.path.join('examples', 'dump', 'random_val_au.pickle'), 'wb') as fp: + pickle.dump(au_data, fp) +with open(os.path.join('examples', 'dump', 'random_val_gaze.pickle'), 'wb') as fp: + gaze = {'rot_trans': rot_tran, 'rot_quat': rot_quat, 'anchor_t_shape': anchor_t_shape} + pickle.dump(gaze, fp) + +''' STEP 4: RUN audio->landmark network ''' +model = Audio2landmark_model(opt_parser, jpg_shape=shape_3d) +if len(opt_parser.reuse_train_emb_list) == 0: + model.test(au_emb=au_emb) +else: + model.test(au_emb=None) + +''' STEP 5: de-normalize the output to the original image scale ''' +fls = glob.glob1('examples', 'pred_fls_*.txt') +fls.sort() + +for i in range(0, len(fls)): + fl = np.loadtxt(os.path.join('examples', fls[i])).reshape((-1, 68, 3)) + fl[:, :, 0:2] = -fl[:, :, 0:2] + fl[:, :, 0:2] = fl[:, :, 0:2] / scale - shift + + if ADD_NAIVE_EYE: + fl = util.add_naive_eye(fl) + + # additional smooth + fl = fl.reshape((-1, 204)) + fl[:, :48 * 3] = savgol_filter(fl[:, :48 * 3], 15, 3, axis=0) + fl[:, 48 * 3:] = savgol_filter(fl[:, 48 * 3:], 5, 3, axis=0) + fl = fl.reshape((-1, 68, 3)) + + ''' STEP 6: Imag2image translation ''' + model = Image_translation_block(opt_parser, single_test=True) + with torch.no_grad(): + model.single_test(jpg=img, fls=fl, filename=fls[i], prefix=os.path.splitext(os.path.basename(opt_parser.jpg))[0]) + print('finish image2image gen') + os.remove(os.path.join('examples', fls[i])) \ No newline at end of file diff --git a/Makittalk/main_end2end_cartoon.py b/Makittalk/main_end2end_cartoon.py new file mode 100644 index 00000000..792262d5 --- /dev/null +++ b/Makittalk/main_end2end_cartoon.py @@ -0,0 +1,232 @@ +""" + # Copyright 2020 Adobe + # All Rights Reserved. + + # NOTICE: Adobe permits you to use, modify, and distribute this file in + # accordance with the terms of the Adobe license agreement accompanying + # it. + +""" + +import sys +sys.path.append('thirdparty/AdaptiveWingLoss') +import os, glob +import numpy as np +import argparse +import pickle +from src.autovc.AutoVC_mel_Convertor_retrain_version import AutoVC_mel_Convertor +import shutil + +ADD_NAIVE_EYE = False +GEN_AUDIO = True +GEN_FLS = True + +DEMO_CH = 'wilk.png' + +parser = argparse.ArgumentParser() +parser.add_argument('--jpg', type=str, required=True, help='Puppet image name to animate (with filename extension), e.g. wilk.png') +parser.add_argument('--jpg_bg', type=str, required=True, help='Puppet image background (with filename extension), e.g. wilk_bg.jpg') +parser.add_argument('--inner_lip', default=False, action='store_true', help='add this if the puppet is created with only inner lip landmarks') + +parser.add_argument('--out', type=str, default='out.mp4') + +parser.add_argument('--load_AUTOVC_name', type=str, default='examples/ckpt/ckpt_autovc.pth') +parser.add_argument('--load_a2l_G_name', type=str, default='examples/ckpt/ckpt_speaker_branch.pth') #ckpt_audio2landmark_g.pth') # +parser.add_argument('--load_a2l_C_name', type=str, default='examples/ckpt/ckpt_content_branch.pth') #ckpt_audio2landmark_c.pth') +parser.add_argument('--load_G_name', type=str, default='examples/ckpt/ckpt_116_i2i_comb.pth') #ckpt_i2i_finetune_150.pth') #ckpt_image2image.pth') # + +parser.add_argument('--amp_lip_x', type=float, default=2.0) +parser.add_argument('--amp_lip_y', type=float, default=2.0) +parser.add_argument('--amp_pos', type=float, default=0.5) +parser.add_argument('--reuse_train_emb_list', type=str, nargs='+', default=[]) # ['E_kmpT-EfOg']) # ['E_kmpT-EfOg']) # ['45hn7-LXDX8']) + + +parser.add_argument('--add_audio_in', default=False, action='store_true') +parser.add_argument('--comb_fan_awing', default=False, action='store_true') +parser.add_argument('--output_folder', type=str, default='examples_cartoon') + +#### NEW POSE MODEL +parser.add_argument('--test_end2end', default=True, action='store_true') +parser.add_argument('--dump_dir', type=str, default='', help='') +parser.add_argument('--pos_dim', default=7, type=int) +parser.add_argument('--use_prior_net', default=True, action='store_true') +parser.add_argument('--transformer_d_model', default=32, type=int) +parser.add_argument('--transformer_N', default=2, type=int) +parser.add_argument('--transformer_heads', default=2, type=int) +parser.add_argument('--spk_emb_enc_size', default=16, type=int) +parser.add_argument('--init_content_encoder', type=str, default='') +parser.add_argument('--lr', type=float, default=1e-3, help='learning rate') +parser.add_argument('--reg_lr', type=float, default=1e-6, help='weight decay') +parser.add_argument('--write', default=False, action='store_true') +parser.add_argument('--segment_batch_size', type=int, default=512, help='batch size') +parser.add_argument('--emb_coef', default=3.0, type=float) +parser.add_argument('--lambda_laplacian_smooth_loss', default=1.0, type=float) +parser.add_argument('--use_11spk_only', default=False, action='store_true') + + +opt_parser = parser.parse_args() + +DEMO_CH = opt_parser.jpg.split('.')[0] + +shape_3d = np.loadtxt('examples_cartoon/{}_face_close_mouth.txt'.format(DEMO_CH)) + +''' STEP 3: Generate audio data as input to audio branch ''' +au_data = [] +au_emb = [] +ains = glob.glob1('examples', '*.wav') +ains = [item for item in ains if item is not 'tmp.wav'] +ains.sort() +for ain in ains: + os.system('ffmpeg -y -loglevel error -i examples/{} -ar 16000 examples/tmp.wav'.format(ain)) + shutil.copyfile('examples/tmp.wav', 'examples/{}'.format(ain)) + + # au embedding + from thirdparty.resemblyer_util.speaker_emb import get_spk_emb + me, ae = get_spk_emb('examples/{}'.format(ain)) + au_emb.append(me.reshape(-1)) + + print('Processing audio file', ain) + c = AutoVC_mel_Convertor('examples') + au_data_i = c.convert_single_wav_to_autovc_input(audio_filename=os.path.join('examples', ain), + autovc_model_path=opt_parser.load_AUTOVC_name) + au_data += au_data_i + # os.remove(os.path.join('examples', 'tmp.wav')) +if(os.path.isfile('examples/tmp.wav')): + os.remove('examples/tmp.wav') + +fl_data = [] +rot_tran, rot_quat, anchor_t_shape = [], [], [] +for au, info in au_data: + au_length = au.shape[0] + fl = np.zeros(shape=(au_length, 68 * 3)) + fl_data.append((fl, info)) + rot_tran.append(np.zeros(shape=(au_length, 3, 4))) + rot_quat.append(np.zeros(shape=(au_length, 4))) + anchor_t_shape.append(np.zeros(shape=(au_length, 68 * 3))) + +if(os.path.exists(os.path.join('examples', 'dump', 'random_val_fl.pickle'))): + os.remove(os.path.join('examples', 'dump', 'random_val_fl.pickle')) +if(os.path.exists(os.path.join('examples', 'dump', 'random_val_fl_interp.pickle'))): + os.remove(os.path.join('examples', 'dump', 'random_val_fl_interp.pickle')) +if(os.path.exists(os.path.join('examples', 'dump', 'random_val_au.pickle'))): + os.remove(os.path.join('examples', 'dump', 'random_val_au.pickle')) +if (os.path.exists(os.path.join('examples', 'dump', 'random_val_gaze.pickle'))): + os.remove(os.path.join('examples', 'dump', 'random_val_gaze.pickle')) + +with open(os.path.join('examples', 'dump', 'random_val_fl.pickle'), 'wb') as fp: + pickle.dump(fl_data, fp) +with open(os.path.join('examples', 'dump', 'random_val_au.pickle'), 'wb') as fp: + pickle.dump(au_data, fp) +with open(os.path.join('examples', 'dump', 'random_val_gaze.pickle'), 'wb') as fp: + gaze = {'rot_trans':rot_tran, 'rot_quat':rot_quat, 'anchor_t_shape':anchor_t_shape} + pickle.dump(gaze, fp) + + +''' STEP 4: RUN audio->landmark network''' +from src.approaches.train_audio2landmark import Audio2landmark_model +model = Audio2landmark_model(opt_parser, jpg_shape=shape_3d) +if(len(opt_parser.reuse_train_emb_list) == 0): + model.test(au_emb=au_emb) +else: + model.test(au_emb=None) +print('finish gen fls') + +''' STEP 5: de-normalize the output to the original image scale ''' +fls_names = glob.glob1('examples_cartoon', 'pred_fls_*.txt') +fls_names.sort() + +for i in range(0,len(fls_names)): + ains = glob.glob1('examples', '*.wav') + ains.sort() + ain = ains[i] + fl = np.loadtxt(os.path.join('examples_cartoon', fls_names[i])).reshape((-1, 68,3)) + output_dir = os.path.join('examples_cartoon', fls_names[i][:-4]) + try: + os.makedirs(output_dir) + except: + pass + + from util.utils import get_puppet_info + + bound, scale, shift = get_puppet_info(DEMO_CH, ROOT_DIR='examples_cartoon') + + fls = fl.reshape((-1, 68, 3)) + + fls[:, :, 0:2] = -fls[:, :, 0:2] + fls[:, :, 0:2] = (fls[:, :, 0:2] / scale) + fls[:, :, 0:2] -= shift.reshape(1, 2) + + fls = fls.reshape(-1, 204) + + # additional smooth + from scipy.signal import savgol_filter + fls[:, 0:48*3] = savgol_filter(fls[:, 0:48*3], 17, 3, axis=0) + fls[:, 48*3:] = savgol_filter(fls[:, 48*3:], 11, 3, axis=0) + fls = fls.reshape((-1, 68, 3)) + + # if (DEMO_CH in ['paint', 'mulaney', 'cartoonM', 'beer', 'color', 'JohnMulaney', 'vangogh', 'jm', 'roy', 'lineface']): + if(not opt_parser.inner_lip): + r = list(range(0, 68)) + fls = fls[:, r, :] + fls = fls[:, :, 0:2].reshape(-1, 68 * 2) + fls = np.concatenate((fls, np.tile(bound, (fls.shape[0], 1))), axis=1) + fls = fls.reshape(-1, 160) + + else: + r = list(range(0, 48)) + list(range(60, 68)) + fls = fls[:, r, :] + fls = fls[:, :, 0:2].reshape(-1, 56 * 2) + fls = np.concatenate((fls, np.tile(bound, (fls.shape[0], 1))), axis=1) + fls = fls.reshape(-1, 112 + bound.shape[1]) + + np.savetxt(os.path.join(output_dir, 'warped_points.txt'), fls, fmt='%.2f') + + # static_points.txt + static_frame = np.loadtxt(os.path.join('examples_cartoon', '{}_face_open_mouth.txt'.format(DEMO_CH))) + static_frame = static_frame[r, 0:2] + static_frame = np.concatenate((static_frame, bound.reshape(-1, 2)), axis=0) + np.savetxt(os.path.join(output_dir, 'reference_points.txt'), static_frame, fmt='%.2f') + + # triangle_vtx_index.txt + shutil.copy(os.path.join('examples_cartoon', DEMO_CH + '_delauney_tri.txt'), + os.path.join(output_dir, 'triangulation.txt')) + + os.remove(os.path.join('examples_cartoon', fls_names[i])) + + # ============================================== + # Step 4 : Vector art morphing + # ============================================== + warp_exe = os.path.join(os.getcwd(), 'facewarp', 'facewarp.exe') + import os + + if (os.path.exists(os.path.join(output_dir, 'output'))): + shutil.rmtree(os.path.join(output_dir, 'output')) + os.mkdir(os.path.join(output_dir, 'output')) + os.chdir('{}'.format(os.path.join(output_dir, 'output'))) + cur_dir = os.getcwd() + print(cur_dir) + + if(os.name == 'nt'): + ''' windows ''' + os.system('{} {} {} {} {} {}'.format( + warp_exe, + os.path.join(cur_dir, '..', '..', opt_parser.jpg), + os.path.join(cur_dir, '..', 'triangulation.txt'), + os.path.join(cur_dir, '..', 'reference_points.txt'), + os.path.join(cur_dir, '..', 'warped_points.txt'), + os.path.join(cur_dir, '..', '..', opt_parser.jpg_bg), + '-novsync -dump')) + else: + ''' linux ''' + os.system('wine {} {} {} {} {} {}'.format( + warp_exe, + os.path.join(cur_dir, '..', '..', opt_parser.jpg), + os.path.join(cur_dir, '..', 'triangulation.txt'), + os.path.join(cur_dir, '..', 'reference_points.txt'), + os.path.join(cur_dir, '..', 'warped_points.txt'), + os.path.join(cur_dir, '..', '..', opt_parser.jpg_bg), + '-novsync -dump')) + os.system('ffmpeg -y -r 62.5 -f image2 -i "%06d.tga" -i {} -pix_fmt yuv420p -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" -shortest -strict -2 {}'.format( + os.path.join(cur_dir, '..', '..', '..', 'examples', ain), + os.path.join(cur_dir, '..', 'out.mp4') + )) diff --git a/Makittalk/main_gen_new_puppet.py b/Makittalk/main_gen_new_puppet.py new file mode 100644 index 00000000..fa5f5fc9 --- /dev/null +++ b/Makittalk/main_gen_new_puppet.py @@ -0,0 +1,198 @@ +import sys +from facewarp.gen_puppet_utils import * + +''' ================================================ + FOA face landmark detection +================================================ ''' + +data_dir = out_dir = 'examples_cartoon' +test_data = sys.argv[1] # for example 'roy_example.png' +CH = test_data[:-4] +use_gt_bb = False + +if(not os.path.exists(os.path.join(data_dir, CH + '.pts'))): + + from thirdparty.face_of_art.menpo_functions import * + from thirdparty.face_of_art.deep_heatmaps_model_fusion_net import DeepHeatmapsModel + + model_path = 'examples/ckpt/deep_heatmaps-60000' # model for estimation stage + pdm_path = 'thirdparty/face_of_art/pdm_clm_models/pdm_models/' # models for correction stage + clm_path = 'thirdparty/face_of_art/pdm_clm_models/clm_models/g_t_all' # model for tuning stage + + outline_tune = True # if true use tuning stage on eyebrows+jaw, else use tuning stage on jaw only + map_landmarks_to_original_image = True # if True, landmark predictions will be mapped to match original + # input image size. otherwise the predicted landmarks will match the cropped version (256x256) of the images + + # load images + bb_dir = os.path.join(data_dir, 'Bounding_Boxes') + bb_dictionary = load_bb_dictionary(bb_dir, mode='TEST', test_data=test_data) + bb_type = 'init' + + img_list = load_menpo_image_list( + img_dir=data_dir, test_data=test_data, train_crop_dir=data_dir, img_dir_ns=data_dir, bb_type=bb_type, + bb_dictionary=bb_dictionary, mode='TEST', return_transform=map_landmarks_to_original_image) + + # load model + heatmap_model = DeepHeatmapsModel( + mode='TEST', img_path=data_dir, test_model_path=model_path, test_data=test_data, menpo_verbose=False) + + print ("\npredicting landmarks for: "+os.path.join(data_dir, test_data)) + print ("\nsaving landmarks to: "+out_dir) + for i, img in enumerate(img_list): + if i == 0: + reuse = None + else: + reuse = True + + preds = heatmap_model.get_landmark_predictions(img_list=[img], pdm_models_dir=pdm_path, clm_model_path=clm_path, + reuse=reuse, map_to_input_size=map_landmarks_to_original_image) + + if map_landmarks_to_original_image: + img = img[0] + + if outline_tune: + pred_lms = preds['ECpTp_out'] + else: + pred_lms = preds['ECpTp_jaw'] + + mio.export_landmark_file(PointCloud(pred_lms[0]), os.path.join(out_dir, img.path.stem + '.pts'), + overwrite=True) + + print ("\nFOA landmark detection DONE!") + + +''' ==================================================================== + opencv vis and refine landmark + +1. visualize the automatic detection result from FOA approach +2. click on landmarks and move them if they are not correct + +Press Q to save landmarks and continue. +==================================================================== ''' + +import cv2 +import numpy as np +import os + +if(os.path.exists(os.path.join(data_dir, CH + '_face_open_mouth.txt'))): + pts0 = np.loadtxt(os.path.join(data_dir, CH + '_face_open_mouth.txt')) + pts0 = pts0[:, 0:2] +else: + f = open(os.path.join(data_dir, test_data[:-4] + '.pts'), 'r') + lines = f.readlines() + pts = [] + for i in range(3, 3+68): + line = lines[i] + line = line[:-1].split(' ') + pts += [float(item) for item in line] + pts0 = np.array(pts).reshape((68, 2)) + +pts = np.copy(pts0) +img0 = cv2.imread(os.path.join(data_dir, test_data)) +img = np.copy(img0) +node = -1 + + +def click_adjust_wireframe(event, x, y, flags, param): + global img, pts, node + + def update_img(node, button_up=False): + global img, pts + + # update carton points object and get fresh pts list + pts[node, 0], pts[node, 1] = x, y + + img = np.copy(img0) + draw_landmarks(img, pts) + + # zoom-in feature + if (not button_up): + zoom_in_scale = 2 + zoom_in_box_size = int(150 / zoom_in_scale) + zoom_in_range = int(np.min([zoom_in_box_size, x, y, + (img.shape[0] - y) / 2 / zoom_in_scale, + (img.shape[1] - x) / 2 / zoom_in_scale])) + + img_zoom_in = img[y - zoom_in_range:y + zoom_in_range, + x - zoom_in_range:x + zoom_in_range].copy() + img_zoom_in = cv2.resize(img_zoom_in, (0, 0), fx=zoom_in_scale, + fy=zoom_in_scale) + cv2.drawMarker(img_zoom_in, (zoom_in_range * zoom_in_scale, + zoom_in_range * zoom_in_scale), + (0, 0, 255), + markerType=cv2.MARKER_CROSS, markerSize=30, + thickness=2, line_type=cv2.LINE_AA) + height, width, depth = np.shape(img_zoom_in) + + img[y:y + height, x:x + width] = img_zoom_in + cv2.rectangle(img, (x, y), (x + height, y + width), + (0, 0, 255), thickness=2) + + + if event == cv2.EVENT_LBUTTONDOWN: + # search for nearest point + node = closest_node((x, y), pts) + if(node >=0): + update_img(node) + + if event == cv2.EVENT_LBUTTONUP: + node = closest_node((x, y), pts) + if (node >= 0): + update_img(node, button_up=True) + node = -1 + + if event == cv2.EVENT_MOUSEMOVE: + # redraw figure + if (node != -1): + update_img(node) + +draw_landmarks(img, pts) + +cv2.namedWindow("img", cv2.WINDOW_NORMAL) +cv2.setMouseCallback("img", click_adjust_wireframe) + +while(True): + cv2.imshow('img', img) + key = cv2.waitKey(1) + if key == ord("q"): + break +cv2.destroyAllWindows() + +print('vis and refine landmark Done!') +pts = np.concatenate([pts, np.ones((68, 1))], axis=1) +np.savetxt(os.path.join(data_dir, '{}_face_open_mouth.txt'.format(CH)), pts, fmt='%.4f') + + +''' ================================================================= + find closed mouth landmark and normalize + +Input: param are used to change closed mouth strength + param[0]: larger -> outer-upper lip higher + param[1]: larger -> outer-lower lip higher + param[2]: larger -> inner-upper lip higher + param[3]: larger -> inner-lower lip higher + +Output: saved as CH_face_open_mouth_norm.txt + CH_scale_shift.txt + CH_face_close_mouth.txt + +Press Q or close the image window to continue. +================================================================= ''' + + +norm_anno(data_dir, CH, param=[0.7, 0.4, 0.5, 0.5], show=True) + + +''' ================================================================= + delauney tri + +Input: INNER_ONLY indicates whether use the inner lip landmarks only + +Output: saved as CH_delauney_tri.txt + +Press any key to continue. +================================================================= ''' + + +delauney_tri(data_dir, test_data, INNER_ONLY=False) + diff --git a/Makittalk/main_train_content.py b/Makittalk/main_train_content.py new file mode 100644 index 00000000..12d83579 --- /dev/null +++ b/Makittalk/main_train_content.py @@ -0,0 +1,92 @@ +""" + # Copyright 2020 Adobe + # All Rights Reserved. + + # NOTICE: Adobe permits you to use, modify, and distribute this file in + # accordance with the terms of the Adobe license agreement accompanying + # it. + +""" + +import os, glob +import numpy as np +import cv2 +import argparse +import platform +import torch +from util.utils import try_mkdir +from src.approaches.train_content import Audio2landmark_model + + +ROOT_DIR = r'/mnt/ntfs/Dataset/TalkingToon/Obama_for_train' +DEMO_CH = '' + +parser = argparse.ArgumentParser() + +parser.add_argument('--root_dir', type=str, default=ROOT_DIR, help='Root dir for data') +parser.add_argument('--nepoch', type=int, default=1001, help='number of epochs to train for') +parser.add_argument('--batch_size', type=int, default=1, help='batch size') +parser.add_argument('--in_batch_nepoch', type=int, default=1, help='') +parser.add_argument('--first_in_batch_nepoch', type=int, default=1, help='') +parser.add_argument('--segment_batch_size', type=int, default=128, help='batch size') +parser.add_argument('--num_window_frames', type=int, default=18, help='') +parser.add_argument('--num_window_step', type=int, default=1, help='') +parser.add_argument('--dump_dir', type=str, default='', help='') +parser.add_argument('--dump_file_name', type=str, default='celeb_withrot', help='') +parser.add_argument('--lr', type=float, default=1e-4, help='learning rate') +parser.add_argument('--reg_lr', type=float, default=0., help='weight decay') +parser.add_argument('--drop_out', type=float, default=0.5, help='drop out') +parser.add_argument('--verbose', type=int, default=1, help='0 - detail, 2 - simplify') +parser.add_argument('--write', default=False, action='store_true') + +parser.add_argument('--add_pos', default=False, action='store_true') +parser.add_argument('--use_motion_loss', default=False, action='store_true') + + +parser.add_argument('--name', type=str, default='tmp') +parser.add_argument('--puppet_name', type=str, default=DEMO_CH) + +parser.add_argument('--in_size', type=int, default=80) + +parser.add_argument('--use_lip_weight', default=True, action='store_false') +parser.add_argument('--lambda_mse_loss', default=1.0, type=float) +parser.add_argument('--show_animation', default=False, action='store_true') + +# model +parser.add_argument('--use_prior_net', default=True, action='store_false') +parser.add_argument('--hidden_size', default=256, type=int) +parser.add_argument('--load_a2l_C_name', type=str, default='') +# arch +parser.add_argument('--use_reg_as_std', default=True, action='store_false') +parser.add_argument('--lambda_laplacian_smooth_loss', default=1.0, type=float) + +# test +parser.add_argument('--test_emb', default=False, action='store_true') +parser.add_argument('--train', default=False, action='store_true') +parser.add_argument('--test_end2end', default=False, action='store_true') + +# save model +parser.add_argument('--jpg_freq', type=int, default=1, help='') +parser.add_argument('--ckpt_epoch_freq', type=int, default=1, help='') +parser.add_argument('--random_clip_num', type=int, default=2, help='') + + +opt_parser = parser.parse_args() + +root_dir = ROOT_DIR +# opt_parser.root_dir = ROOT_DIR +opt_parser.dump_dir = os.path.join(opt_parser.root_dir, 'dump') +opt_parser.ckpt_dir = os.path.join(opt_parser.root_dir, 'ckpt', opt_parser.name) +try_mkdir(opt_parser.ckpt_dir) +opt_parser.log_dir = os.path.join(opt_parser.root_dir, 'log') + +# make directory for nn outputs +try_mkdir(opt_parser.dump_dir.replace('dump','nn_result')) +try_mkdir(os.path.join(opt_parser.dump_dir.replace('dump', 'nn_result'), opt_parser.name)) + + +model = Audio2landmark_model(opt_parser) +if(opt_parser.train): + model.train() +else: + model.test() diff --git a/Makittalk/main_train_image_translation.py b/Makittalk/main_train_image_translation.py new file mode 100644 index 00000000..af807c58 --- /dev/null +++ b/Makittalk/main_train_image_translation.py @@ -0,0 +1,90 @@ +""" + # Copyright 2020 Adobe + # All Rights Reserved. + + # NOTICE: Adobe permits you to use, modify, and distribute this file in + # accordance with the terms of the Adobe license agreement accompanying + # it. + +""" + +import sys +sys.path.append('thirdparty/AdaptiveWingLoss') +import os, glob +import numpy as np +import cv2 +import argparse +from src.dataset.image_translation import landmark_extraction, landmark_image_to_data +from approaches.train_image_translation import Image_translation_block +import platform +import torch + + +if platform.release() == '4.4.0-83-generic': + src_dir = r'/mnt/ntfs/Dataset/TalkingToon/VoxCeleb2_imagetranslation/raw_fl3d' + mp4_dir = r'/mnt/ntfs/Dataset/VoxCeleb2/train_set/dev/mp4' + jpg_dir = r'img_output' + ckpt_dir = r'img_output' + log_dir = r'img_output' +else: # 3.10.0-957.21.2.el7.x86_64 + # root = r'/mnt/nfs/scratch1/yangzhou/VoxCeleb2_imagetranslation' + root = r'/mnt/nfs/scratch1/yangzhou/PreprocessedVox_imagetranslation' + src_dir = os.path.join(root, 'raw_fl3d') + # mp4_dir = r'/mnt/nfs/work1/kalo/yangzhou/VoxCeleb2/train_set/dev/mp4' + mp4_dir = r'/mnt/nfs/scratch1/yangzhou/PreprocessedVox_mp4' + jpg_dir = os.path.join(root, 'tmp_v') + ckpt_dir = os.path.join(root, 'ckpt') + log_dir = os.path.join(root, 'log') + +''' Step 1. Data preparation ''' +# landmark extraction +# landmark_extraction(int(sys.argv[1]), int(sys.argv[2])) + +# save image data ahead -> saved file too large, will create data online +# landmark_image_to_data(0, 0, show=False) + +''' Step 2. Train the network ''' +parser = argparse.ArgumentParser() +parser.add_argument('--nepoch', type=int, default=150, help='number of epochs to train for') +parser.add_argument('--batch_size', type=int, default=8, help='batch size') +parser.add_argument('--num_frames', type=int, default=1, help='') +parser.add_argument('--num_workers', type=int, default=4, help='number of frames extracted from each video') +parser.add_argument('--lr', type=float, default=0.0001, help='') + +parser.add_argument('--write', default=False, action='store_true') +parser.add_argument('--train', default=False, action='store_true') +parser.add_argument('--name', type=str, default='tmp') +parser.add_argument('--test_speed', default=False, action='store_true') + +parser.add_argument('--jpg_dir', type=str, default=jpg_dir) +parser.add_argument('--ckpt_dir', type=str, default=ckpt_dir) +parser.add_argument('--log_dir', type=str, default=log_dir) + +parser.add_argument('--jpg_freq', type=int, default=50, help='') +parser.add_argument('--ckpt_last_freq', type=int, default=1000, help='') +parser.add_argument('--ckpt_epoch_freq', type=int, default=1, help='') + +parser.add_argument('--load_G_name', type=str, default='') +parser.add_argument('--use_vox_dataset', type=str, default='raw') + + +parser.add_argument('--add_audio_in', default=False, action='store_true') +parser.add_argument('--comb_fan_awing', default=False, action='store_true') +parser.add_argument('--fan_2or3D', type=str, default='3D') + +parser.add_argument('--single_test', type=str, default='') + +opt_parser = parser.parse_args() + + +model = Image_translation_block(opt_parser) + +if(opt_parser.single_test != ''): + with torch.no_grad(): + model.single_test() + +if(opt_parser.train): + model.train() +else: + with torch.no_grad(): + model.test() \ No newline at end of file diff --git a/Makittalk/main_train_speaker_aware.py b/Makittalk/main_train_speaker_aware.py new file mode 100644 index 00000000..f6247d0f --- /dev/null +++ b/Makittalk/main_train_speaker_aware.py @@ -0,0 +1,140 @@ +""" + # Copyright 2020 Adobe + # All Rights Reserved. + + # NOTICE: Adobe permits you to use, modify, and distribute this file in + # accordance with the terms of the Adobe license agreement accompanying + # it. + +""" + +import os, glob +import numpy as np +import cv2 +import argparse +import platform +import torch +from util.utils import try_mkdir +from approaches.train_speaker_aware import Speaker_aware_branch + + +if platform.release() == '4.4.0-83-generic': + ROOT_DIR = r'/mnt/ntfs/Dataset/TalkingToon/VoxCeleb2' +else: # 3.10.0-957.21.2.el7.x86_64 + ROOT_DIR = r'/mnt/nfs/work1/kalo/yangzhou/TalkingToon/VoxCeleb2' + +DEMO_CH = '' + +parser = argparse.ArgumentParser() +parser.add_argument('--nepoch', type=int, default=1001, help='number of epochs to train for') +parser.add_argument('--batch_size', type=int, default=1, help='batch size') +parser.add_argument('--in_batch_nepoch', type=int, default=1, help='') +parser.add_argument('--first_in_batch_nepoch', type=int, default=1, help='') +parser.add_argument('--segment_batch_size', type=int, default=512, help='batch size') +parser.add_argument('--num_window_frames', type=int, default=18, help='') +parser.add_argument('--num_window_frames_seq', type=int, default=18, help='') +parser.add_argument('--num_window_frames_sync', type=int, default=18, help='') +parser.add_argument('--num_window_step', type=int, default=1, help='') +parser.add_argument('--dump_dir', type=str, default='', help='') +parser.add_argument('--dump_file_name', type=str, default='celeb_normrot', help='') +parser.add_argument('--lr', type=float, default=1e-3, help='learning rate') +parser.add_argument('--reg_lr', type=float, default=1e-6, help='weight decay') +parser.add_argument('--drop_out', type=float, default=0, help='drop out') +parser.add_argument('--verbose', type=int, default=1, help='0 - detail, 2 - simplify') +parser.add_argument('--write', default=False, action='store_true') + +parser.add_argument('--add_pos', default=False, action='store_true') +parser.add_argument('--use_motion_loss', default=False, action='store_true') + + +parser.add_argument('--name', type=str, default='tmp') +parser.add_argument('--puppet_name', type=str, default=DEMO_CH) + +parser.add_argument('--in_size', type=int, default=80) + +parser.add_argument('--use_lip_weight', default=False, action='store_true') +parser.add_argument('--use_adain', default=False, action='store_true') +parser.add_argument('--use_residual', default=False, action='store_true') +parser.add_argument('--use_norm_emb', default=False, action='store_true') +parser.add_argument('--use_cycle_loss', default=False, action='store_true') +parser.add_argument('--lambda_cycle_loss', default=1.0, type=float) +parser.add_argument('--emb_coef', default=3.0, type=float) + +parser.add_argument('--freeze_content_emb', default=False, action='store_true') +parser.add_argument('--pretrain_g', default=False, action='store_true') + +parser.add_argument('--spk_emb_enc_size', default=16, type=int) +parser.add_argument('--c_enc_hidden_size', default=256, type=int) +parser.add_argument('--lstm_g_hidden_size', default=256, type=int) +parser.add_argument('--projection_size', default=512, type=int) + +parser.add_argument('--use_addinfo_format', default='motion_and_pos') +parser.add_argument('--l2_on_fls_without_traj', default=False, action='store_true') +parser.add_argument('--train_with_grad_penalty', default=False, action='store_true') +parser.add_argument('--train_DL', default=-1.0, type=float) +parser.add_argument('--train_DT', default=-1.0, type=float) +parser.add_argument('--train_G_only', default=False, action='store_true') +parser.add_argument('--lambda_mse_loss', default=1.0, type=float) +parser.add_argument('--teacher_force', default=0.0, type=float) +parser.add_argument('--debug_version', default='', type=str) +parser.add_argument('--lambda_add_info_loss', default=1.0, type=float) + + +parser.add_argument('--show_animation', default=False, action='store_true') + + + +# model +parser.add_argument('--pos_dim', default=7, type=int) +parser.add_argument('--use_prior_net', default=True, action='store_true') +parser.add_argument('--transformer_d_model', default=32, type=int) +parser.add_argument('--transformer_N', default=2, type=int) +parser.add_argument('--transformer_heads', default=2, type=int) +parser.add_argument('--load_a2l_C_name', type=str, default='examples/ckpt/ckpt_audio2landmark_c.pth') +parser.add_argument('--init_content_encoder', type=str, default='examples/ckpt/ckpt_audio2landmark_c.pth') # 'tt_lipwpre_prior_useclose/ckpt_last_epoch_20.pth') +parser.add_argument('--load_a2l_G_name', type=str, default='/mnt/ntfs/Dataset/TalkingToon/VoxCeleb2/ckpt/local_da_merge_3/ckpt_e_50.pth') # + + +# data +parser.add_argument('--use_11spk_only', default=True, action='store_true') + +# arch +parser.add_argument('--use_reg_as_std', default=True, action='store_false') +parser.add_argument('--lambda_laplacian_smooth_loss', default=1.0, type=float) + +# test +parser.add_argument('--test_emb', default=False, action='store_true') +parser.add_argument('--train', default=False, action='store_true') +parser.add_argument('--test_end2end', default=False, action='store_true') + +# save model +parser.add_argument('--jpg_freq', type=int, default=25, help='') +parser.add_argument('--ckpt_epoch_freq', type=int, default=25, help='') + +AMP = {'default':[2.5, 2.5, 1.0]} +if(DEMO_CH not in AMP.keys()): + AMP[DEMO_CH] = AMP['default'] + +parser.add_argument('--amp_lip_x', type=float, default=AMP[DEMO_CH][0]) +parser.add_argument('--amp_lip_y', type=float, default=AMP[DEMO_CH][1]) +parser.add_argument('--amp_pos', type=float, default=AMP[DEMO_CH][2]) + +opt_parser = parser.parse_args() + +root_dir = ROOT_DIR +opt_parser.root_dir = ROOT_DIR +opt_parser.dump_dir = os.path.join(root_dir, 'dump') +opt_parser.ckpt_dir = os.path.join(root_dir, 'ckpt', opt_parser.name) +try_mkdir(opt_parser.ckpt_dir) +opt_parser.log_dir = os.path.join(root_dir, 'log') + +# make directory for nn outputs +try_mkdir(opt_parser.dump_dir.replace('dump','nn_result')) +try_mkdir(os.path.join(opt_parser.dump_dir.replace('dump', 'nn_result'), opt_parser.name)) + + +model = Speaker_aware_branch(opt_parser) +if(opt_parser.train): + model.train() +else: + model.test() \ No newline at end of file diff --git a/Makittalk/process_video.py b/Makittalk/process_video.py new file mode 100644 index 00000000..7bb3d383 --- /dev/null +++ b/Makittalk/process_video.py @@ -0,0 +1,53 @@ +import os +import cv2 +from moviepy.editor import VideoFileClip +import argparse + +def extract_audio(video_path, output_audio_path): + """提取音频文件""" + video = VideoFileClip(video_path) + video.audio.write_audiofile(output_audio_path) + +def extract_and_crop_image(video_path, output_image_path, frame_number=100): + """截取并裁剪肖像图片""" + cap = cv2.VideoCapture(video_path) + cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number) + ret, frame = cap.read() + if ret: + height, width, _ = frame.shape + center_y, center_x = height // 2, width // 2 + cropped_frame = frame[center_y - 128:center_y + 128, center_x - 128:center_x + 128] + cv2.imwrite(output_image_path, cropped_frame) + else: + print(f"Error: Unable to read frame {frame_number} from {video_path}") + cap.release() + +def main(video_path, jpg_output, wav_output, amp_lip_x, amp_lip_y, amp_pos): + examples_dir = os.path.dirname(jpg_output) + if not os.path.exists(examples_dir): + os.makedirs(examples_dir) + + print(f"Extracting audio to {wav_output}") + extract_audio(video_path, wav_output) + print(f"Extracting and cropping image to {jpg_output}") + extract_and_crop_image(video_path, jpg_output) + + if not os.path.exists(jpg_output): + print(f"Error: Image file {jpg_output} not created.") + return + + print(f"Successfully created:") + print(f" Image file: {jpg_output}") + print(f" Audio file: {wav_output}") + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="从视频中提取音频和肖像图片,并运行 main_end2end.py 脚本") + parser.add_argument('--video', type=str, required=True, help="输入视频文件路径") + parser.add_argument('--jpg_output', type=str, default="examples/output.jpg", help="输出肖像图片文件路径") + parser.add_argument('--wav_output', type=str, default="examples/output.wav", help="输出音频文件路径") + parser.add_argument('--amp_lip_x', type=float, default=2.0, help="嘴唇运动的 X 轴放大系数") + parser.add_argument('--amp_lip_y', type=float, default=2.0, help="嘴唇运动的 Y 轴放大系数") + parser.add_argument('--amp_pos', type=float, default=0.5, help="头部运动位移的放大系数") + args = parser.parse_args() + + main(args.video, args.jpg_output, args.wav_output, args.amp_lip_x, args.amp_lip_y, args.amp_pos) diff --git a/Makittalk/requirements.txt b/Makittalk/requirements.txt new file mode 100644 index 00000000..11453af2 --- /dev/null +++ b/Makittalk/requirements.txt @@ -0,0 +1,10 @@ +ffmpeg-python +opencv-python +face_alignment +scikit-learn +pydub +soundfile +librosa +pysptk +pyworld +resemblyzer