无需Avatarify 无需剪辑工具 一键生成多人版 “蚂蚁呀嘿“视频

2023-10-27

2021年3月1日更新2:

1.调整人脸区域为椭圆,比圆形更贴合脸型,占用的面积变小。

2.修复了人脸出现黑边的问题。

如果人脸区域不合适,可调整ratio参数。

2021年3月1日更新:

1.调整人脸区域为圆形,更贴合脸型,占用的面积变小。

2.增加ratio参数,可以调整人脸区域的面积,默认为1.0,代表圆形区域的半径为脸部的高度。

PaddleGAN套件gitee地址:

https://gitee.com/txyugood/PaddleGAN.git

驱动视频以及音频文件下载地址:

链接: https://pan.baidu.com/s/1scHNJtfFAFpYV4X2pGPKRA

提取码: 5m3f

公众号:人工智能研习社,欢迎大家关注。


抖音上的蚂蚁呀嘿火遍全网,很多小伙伴都不知道如何制作。本文抛弃繁琐的操作,利用PaddleHub与PaddleGAN框架一键生成多人版的”蚂蚁呀嘿“视频。

先放一张效果图:

首先我们需要安装PaddleHub,利用其中的face detection功能来定位照片中人脸。

安装方法如下:

pip install paddlehub==1.6.0

安装之后paddlehub之后,还需要安装一下人脸检测的模型,命令如下:

hub install ultra_light_fast_generic_face_detector_1mb_640 

生成”蚂蚁呀嘿“视频需要用到PaddleGAN套件中的动作迁移功能,所以下一步需要安装PaddleGAN套件。因为我修改了PaddleGAN套件部分代码,所以这个代码已经保存在AIStudio环境中,直接安装就可以了。

AI Stuidio地址:(强烈推荐,fork后可一键运行,无需搭建环境)
https://aistudio.baidu.com/aistudio/projectdetail/1285661

也可以从以下地址下载:

https://gitee.com/txyugood/PaddleGAN.git

使用以下命令安装PaddleGAN。

cd PaddleGAN/
pip install -v -e .

安装PaddleGAN依赖的PaddlePaddle框架。

python -m pip install https://paddle-wheel.bj.bcebos.com/2.0.0-rc0-gpu-cuda10.1-cudnn7-mkl_gcc8.2%2Fpaddlepaddle_gpu-2.0.0rc0.post101-cp37-cp37m-linux_x86_64.whl

此处借用了GT大佬

https://aistudio.baidu.com/aistudio/projectdetail/1584416

项目中的驱动视频。

/home/aistudio/1.jpeg是测试的照片,可以使用右侧的上传功能上传自己的照片,然后替换–source_image 后面的路径后,运行脚本即可。

最终/home/aistudio/output/mayiyahei.mp4就是最终生成的"蚂蚁呀嘿"视频。

可以通过ratio参数调整用于动作迁移的人脸的图片尺寸,1.0代表半径等于人脸高度的圆形区域。

运行脚本生成视频:

cd /home/aistudio/PaddleGAN/applications/
python -u tools/first-order-mayi.py  \
     --driving_video /home/aistudio/MaYiYaHei.mp4 \
     --source_image /home/aistudio/1.jpeg \
     --relative --adapt_scale \
     --output /home/aistudio/output \
     --ratio 1.0

PaddleGAN/application/tools/first-order-mayi.py文件,是生成”蚂蚁呀嘿“视频的主程序。

下面简单解读一下代码:

import argparse

import os
import paddle
from ppgan.apps.first_order_predictor import FirstOrderPredictor
from skimage import img_as_ubyte
import paddlehub as hub
import math
import cv2
import imageio
import numpy as np

parser = argparse.ArgumentParser()
parser.add_argument("--config", default=None, help="path to config")
parser.add_argument("--weight_path",
                    default=None,
                    help="path to checkpoint to restore")
parser.add_argument("--source_image", type=str, help="path to source image")
parser.add_argument("--driving_video", type=str, help="path to driving video")
parser.add_argument("--output", default='output', help="path to output")
parser.add_argument("--relative",
                    dest="relative",
                    action="store_true",
                    help="use relative or absolute keypoint coordinates")
parser.add_argument(
    "--adapt_scale",
    dest="adapt_scale",
    action="store_true",
    help="adapt movement scale based on convex hull of keypoints")

parser.add_argument(
    "--find_best_frame",
    dest="find_best_frame",
    action="store_true",
    help=
    "Generate from the frame that is the most alligned with source. (Only for faces, requires face_aligment lib)"
)

parser.add_argument("--best_frame",
                    dest="best_frame",
                    type=int,
                    default=None,
                    help="Set frame to start from.")
parser.add_argument("--cpu", dest="cpu", action="store_true", help="cpu mode.")
parser.add_argument("--ratio", dest="ratio",type=str,default="1.0", help="area ratio of face")

parser.set_defaults(relative=False)
parser.set_defaults(adapt_scale=False)

if __name__ == "__main__":
    args = parser.parse_args()

    if args.cpu:
        paddle.set_device('cpu')
    cache_path = os.path.join(args.output,"cache")
    if not os.path.exists(cache_path):
        os.makedirs(cache_path)
    image_path = args.source_image
    
    origin_img = cv2.imread(image_path)
    image_width = origin_img.shape[1]
    image_hegiht = origin_img.shape[0]
    ratio = float(args.ratio)
	#获取人脸模型
    module = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_640")
    #对照片进行人脸检测
    face_detecions = module.face_detection(paths = [image_path], visualization=True, output_dir='face_detection_output')
    #获取人脸检测结果
    face_detecions = face_detecions[0]['data']
    
    #截取人脸图片,并保存人脸图片的属性在face_list列表中。
    face_list = []
    for i, face_dect in enumerate(face_detecions):
        left = math.ceil(face_dect['left'])
        right = math.ceil(face_dect['right'])
        top = math.ceil(face_dect['top'])
        bottom = math.ceil(face_dect['bottom'])
        width = right - left
        height = bottom - top
        center_x = left + width // 2
        center_y = top + height // 2
        size = math.ceil(ratio * height)

        new_left = max(center_x - size, 0)
        new_right = min(center_x + size, image_width)

        new_top = max(center_y - size, 0)
        new_bottom = min(center_y + size, image_hegiht)

        origin_img = cv2.imread(image_path)
        face_img = origin_img[new_top:new_bottom, new_left:new_right, :]
        face_height = face_img.shape[0]
        face_width = face_img.shape[1]

        cv2.imwrite(os.path.join(cache_path,'face_{}.jpeg'.format(i)), face_img)

        face_list.append({"path" : os.path.join(cache_path,'face_{}.jpeg'.format(i)),
                            "width":face_width, "height":face_height, 
                            "top":new_top, "bottom":new_bottom,
                            "left":new_left, "right":new_right, "center_x":center_x, "center_y":center_y,
                            "origin_width":width, "origin_height":height})
    #遍历face_list,对每一个人脸进行动作迁移。
    frames = 0
    for face_dict in face_list:
        predictor = FirstOrderPredictor(output=args.output,
                                        weight_path=args.weight_path,
                                        config=args.config,
                                        relative=args.relative,
                                        adapt_scale=args.adapt_scale,
                                        find_best_frame=args.find_best_frame,
                                        best_frame=args.best_frame)
        predictions,fps = predictor.run(face_dict["path"], args.driving_video)
        #将迁移后的结果保存到face_dict中
        face_dict['pre'] = predictions
        frames = len(predictions)
    images = []    
    #遍历动作迁移后的帧,将人脸放置到原图上。
    for i in range(frames):
    	#从原始图像上拷贝一帧图像
        new_frame = origin_img.copy()
        new_frame = new_frame[:,:,[2,1,0]]
        for j, face_dict in enumerate(face_list):
            pre = face_dict["pre"][i]
            face_width = face_dict["width"]
            face_height = face_dict["height"]
            top = face_dict["top"]
            bottom = face_dict["bottom"]
            left = face_dict["left"]
            right = face_dict["right"]
            img = cv2.resize(pre,(face_width, face_height))

            img_expand = np.zeros(origin_img.shape).astype('uint8')
            img_expand[top:bottom, left:right, :] = img_as_ubyte(img)

            mask = np.zeros(origin_img.shape[:2]).astype('uint8')
            center_x = face_dict["center_x"]
            center_y = face_dict["center_y"]
            origin_width = face_dict["origin_width"] 
            origin_height = face_dict["origin_height"]
            #绘制一个椭圆的蒙版,更贴近脸型。
            cv2.ellipse(mask, (int(center_x), int(center_y)), 
                        (math.ceil(ratio * origin_width) - , math.ceil(ratio * origin_height) - 1), 0,0,360,
                        (255,255,255), -1 ,8 ,0)
            #利用蒙版将生成后的帧拷贝到原图上。
            new_frame = cv2.copyTo(img_expand, mask, new_frame)
            if isinstance(new_frame, cv2.UMat):
                new_frame = new_frame.get()

            # cv2.imwrite("face_{}.jpg".format(i), img_expand)
            # cv2.imwrite("test_{}.jpg".format(i), new_frame)
            #方形放置
            # new_frame[top:bottom, left:right, :] = img_as_ubyte(img)
        #将生成后的帧保存。
        images.append(new_frame)
    #将图片合并为视频
    imageio.mimsave(os.path.join(args.output, 'result.mp4'),
                [img_as_ubyte(frame) for frame in images],
                fps=fps)
    #合并音视频
    os.system("ffmpeg -y -i "  + os.path.join(args.output, 'result.mp4') + " -i /home/aistudio/MYYH.mp3 -c:v copy -c:a aac -strict experimental " + os.path.join(args.output, 'mayiyahei.mp4'))

该程序目前还有许多可以改进的地方,后续会继续优化。

推荐使用AI Studio运行该程序,不但有免费的V100算力可使用,还可以方便的一键运行脚本生成视频。

欢迎关注我的公众号:人工智能研习社,分享更多的人工智能技术干货。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无需Avatarify 无需剪辑工具 一键生成多人版 “蚂蚁呀嘿“视频 的相关文章

  • 跨平台客户端Socket 一 数据包定义

    最近网上查找资料并结合很久以前pc游戏中使用的tcp ip代码 整理出cocos2d x 跨平台的客户端网络模块 目前数据包仍是以前的字节码数据形式 后续会修改使用protobuff的数据交换方式 注 代码未测试 先将内容记录下来 Glob
  • Android Studio代码调试大全

    http blog csdn net dd864140130 article details 51560664 Android Studio目前已经成为开发Android的主要工具 用熟了可谓相当顺手 作为开发者 调试并发现bug 进而解决

随机推荐

  • 逆向爬虫17 Scrapy中间件

    逆向爬虫17 Scrapy中间件 在学习Scrapy之前 我们已经学了很多伪装防反爬的爬虫技术 目标 如何在Scrapy框架中也使用这些技术呢 这是本节要讨论的问题 本节要讨论的防反爬技术有 处理登录Cookies 处理UA 处理代理IP
  • css文本超出宽带自动换行

    css文本超出宽带自动换行 样式word wrap break word 效果 样式word wrap break word
  • Minio Browser

    Minio Browser Minio Browser使用Json Web Token来验证JSON RPC请求 初使请求为用户提供的AccessKey和SecretKey生成一个token令牌 目前这些令牌在10小时后到期 这是不可配置的
  • Apisix使用教程

    安装 推荐直接使用Docker来安装启动Apisix 安装docker 首先下载并安装docker https www docker com 下载之后 直接运行安装 安装后打开Docker Desktop 等它启动完 启动完之后 此时就是可
  • 图灵奖得主Judea Pearl:人工智能是如何走出死胡同的?

    作者 Judea Pearl Danna Mackenzie 编辑 Natalie AI 前线导读 人工智能研究专家 Judea Pearl 及其同事领导的因果关系革命突破多年的迷雾 厘清了知识的本质 确立了因果关系研究在科学探索中的核心地
  • 不同视角下的存储协议栈

    复杂度3 5 机密度3 5 最后更新2021 05 03 我们把AIX的存储协议栈归纳一下 从两个不同视角来观察 以AIX驱动实现视角 主要是文件系统驱动程序 被称为内核扩展可能更恰当 不过具体叫什么并不重要 LVM驱动程序 磁盘设备驱动程
  • Java小白一个,可以直接学习SpringBoot来做毕设吗?

    个人建议不要跳过SSM 很多人想要跳过SSM直接上手SpringBoot 但是SpringBoot中自动化配置 条件注解 Java配置等东西都基于Spring的 Java配置是Spring3开始提供的 条件注解也是Spring中的内容 很多
  • AGV轨迹matlab仿真,两轮差速AGV的轨迹跟踪控制研究 Study on Trajectory Tracking Control of Two-Wheel Difference Speed of...

    Software Engineering and Applications Vol 06 No 04 2017 Article ID 21608 9 pages 10 12677 SEA 2017 64007 Study on Trajec
  • QT学习14:QtXlsx操作Excel表

    一 前言 操作excel方式有 QAxObject 和QtXlsx 区别 Qt自带的QAxObject库操作excel的前提是电脑已经安装微软的Office 包含EXCEL 而QtXlsx可以直接使用免装Office且操作更简单 二 QtX
  • CNZZ埋点及点击量统计方法

    1 引入cnzz统计代码 document write unescape 3Cspan id 你的cnzzID 3E 3C span 3E 3Cscript src https s9 cnzz com z stat php 3Fid 3D1
  • Irrlicht引擎Shader渲染的BUG

    修改2 丢人了 回头一看原来的理解还是不够完整 如果在视图空间计算光照等 一般都会将法线变换到视图空间 想当然的做法是用视图矩阵来变换法线 这么做只有在物体没有缩放或是一致性缩放的情况下才是正确的 若是物体有非一致性缩放 uniform s
  • Python多版本管理工具--pyenv

    我们在平时的项目开发或者学习中 有可能使用不同的Python版本 大家都知道Python的版本非常多 如果我们把需要的不同版本的Python都下载到服务器上 管理起来会非常困难 多版本并存又容易互相干扰 搞不好整个服务器的Python环境会
  • WebSocked、SSE、http1.0、http1.1和http2.0之间的关系

    1 WebSocked是个啥 首先 WebSocked是html5搞出来的一种新的协议 所以和http没有什么联系 要说非要有联系就是他借用了http协议来完成一部分的握手 但它和http一样都是一种连接协议 建立在tcp协议之上 使用在应
  • 服务器端Windows系统下SVN配置

    服务器端Windows系统下SVN配置 在局域网或者公网上进行SVN配置 即客户端与服务器端不是同一台电脑 则服务器端需要利用相关软件进行相应配置 客户端配置请参见 Windows系统下SVN 本地配置 所需软件 Visual SVN Se
  • 实证研究的步骤_写一篇论文的大致步骤是什么呢?

    大部分写过论文的人都知道 完成一篇大论文 准备时间少则数月多则数年 一旦准备完成 论文不过数天或数周就可以完成 下面我们简单总结一下写一篇论文的大致步骤有哪些 一 选题 选题是否恰当 对于论文写作有非常大的影响 论文选题可以从本专业未研究过
  • 【仙女踩坑实录】VirtualBox设置中需要禁用硬件虚拟化才能启动虚拟机

    最近在用virtual box做实验 在设置中提示 需要禁用硬件虚拟化才能启动虚拟机 确认按钮灰色 并且无法启动虚拟机 于是重启 进到bios系统 网上说按F2或者根据电脑上的提示再开机的时候一直按就能进入 我没进去 不过幸好 之前设置过g
  • 【编译原理】LL(1)文法分析全过程(FIRST/FLLOW/SELECT集等)实现(c++语言)

    注 本程序只能进行LL 1 文法的分析 非LL 1 文法请转化为LL 1 文法 变量声明 string M 2000 2000 任务分析表 stack
  • JMX+Prometheus监控Grafana展示

    文章目录 概述 Java代码使用PrometheusApi统计监控指标 Prometheus Grafana展示 概述 最近在阅读InLong的源码 发现它采用通过JMX Prometheus进行指标监控 这里做了下延伸将介绍使用JMX P
  • 【配电网重构】高比例清洁能源接入下计及需求响应的配电网重构【IEEE33节点】(Matlab代码实现)

    欢迎来到本博客 博主优势 博客内容尽量做到思维缜密 逻辑清晰 为了方便读者 座右铭 行百里者 半于九十 本文目录如下 目录 1 概述 2 运行结果 2 1 数据 2 2 DG 与负荷 24 h 功率分布曲线 2 3 需求响应措施对重构结果的
  • 无需Avatarify 无需剪辑工具 一键生成多人版 “蚂蚁呀嘿“视频

    2021年3月1日更新2 1 调整人脸区域为椭圆 比圆形更贴合脸型 占用的面积变小 2 修复了人脸出现黑边的问题 如果人脸区域不合适 可调整ratio参数 2021年3月1日更新 1 调整人脸区域为圆形 更贴合脸型 占用的面积变小 2 增加