单图换脸roop源码与环境配置

news2024/9/23 9:26:00

前言

1.roop是新开源了一个单图就可以进行视频换脸的项目,只需要一张所需面部的图像。不需要数据集,不需要训练。

2.大概的测试了一下,正脸换脸效果还不错,融合也比较自然。但如果人脸比较大,最终换出的效果可能会有些模糊。侧脸部分的幅度不宜过大,否则会出现人脸乱飘的情况。在多人场景下,也容易出现混乱。

3.使用简单,在处理单人视频和单人图像还是的换脸效果还是可以的,融合得也不错,适合制作一些小视频或单人图像。

4.效果如下:

 环境安装

1.我这里部署部署环境是win 10、cuda 11.7、cudnn 8.5、GPU是N卡的3060(6G显存),加anaconda3.

2.源码下载,如果用不了git,可以下载打包好的源码和模型。

git clone https://github.com/s0md3v/roop.git
cd roop

3.创建环境

conda create --name roop python=3.10
activate roop
conda install pytorch==2.0.0 torchvision==0.15.0 torchaudio==2.0.0 pytorch-cuda=11.7 -c pytorch -c nvidia
pip install -r requirements.txt

4.安装onnxruntime-gpu推理库

pip install onnxruntime-gpu

5.运行程序

python run.py

运行,它会下载一个500多m的模型,国内的网可能下载得很慢,也可以单独下载之后放到roop根目录下。

7.报错

ffmpeg is not installed!

这个是缺少了FFmpeg,FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。简单说来就是我们可以用它来进行视频的编解码,可以将视频文件转化为视频流,也可以将视频流转存储为视频文件。还有一个重点就是它是开源的。去官网下载后,加到环境变量就可以了。

8.如果在本地的机子跑起来很慢,把它做成服务器的方式运行,这样就可以在网页或者以微信公众 号或者小程序的方式访问,服务器端代码:

#!/usr/bin/env python3

import os
import sys
# single thread doubles performance of gpu-mode - needs to be set before torch import
if any(arg.startswith('--gpu-vendor') for arg in sys.argv):
    os.environ['OMP_NUM_THREADS'] = '1'
import platform
import signal
import shutil
import glob
import argparse
import psutil
import torch
import tensorflow
from pathlib import Path
import multiprocessing as mp
from opennsfw2 import predict_video_frames, predict_image
from flask import Flask, request
# import base64
import numpy as np
from gevent import pywsgi
import cv2, argparse
import time
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

import roop.globals
from roop.swapper import process_video, process_img, process_faces, process_frames
from roop.utils import is_img, detect_fps, set_fps, create_video, add_audio, extract_frames, rreplace
from roop.analyser import get_face_single
import roop.ui as ui

signal.signal(signal.SIGINT, lambda signal_number, frame: quit())
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--face', help='use this face', dest='source_img')
parser.add_argument('-t', '--target', help='replace this face', dest='target_path')
parser.add_argument('-o', '--output', help='save output to this file', dest='output_file')
parser.add_argument('--keep-fps', help='maintain original fps', dest='keep_fps', action='store_true', default=False)
parser.add_argument('--keep-frames', help='keep frames directory', dest='keep_frames', action='store_true', default=False)
parser.add_argument('--all-faces', help='swap all faces in frame', dest='all_faces', action='store_true', default=False)
parser.add_argument('--max-memory', help='maximum amount of RAM in GB to be used', dest='max_memory', type=int)
parser.add_argument('--cpu-cores', help='number of CPU cores to use', dest='cpu_cores', type=int, default=max(psutil.cpu_count() / 2, 1))
parser.add_argument('--gpu-threads', help='number of threads to be use for the GPU', dest='gpu_threads', type=int, default=8)
parser.add_argument('--gpu-vendor', help='choice your GPU vendor', dest='gpu_vendor', default='nvidia', choices=['apple', 'amd', 'intel', 'nvidia'])

args = parser.parse_known_args()[0]

if 'all_faces' in args:
    roop.globals.all_faces = True

if args.cpu_cores:
    roop.globals.cpu_cores = int(args.cpu_cores)

# cpu thread fix for mac
if sys.platform == 'darwin':
    roop.globals.cpu_cores = 1

if args.gpu_threads:
    roop.globals.gpu_threads = int(args.gpu_threads)

# gpu thread fix for amd
if args.gpu_vendor == 'amd':
    roop.globals.gpu_threads = 1

if args.gpu_vendor:
    roop.globals.gpu_vendor = args.gpu_vendor
else:
    roop.globals.providers = ['CPUExecutionProvider']

sep = "/"
if os.name == "nt":
    sep = "\\"


def limit_resources():
    # prevent tensorflow memory leak
    gpus = tensorflow.config.experimental.list_physical_devices('GPU')
    for gpu in gpus:
        tensorflow.config.experimental.set_memory_growth(gpu, True)
    if args.max_memory:
        memory = args.max_memory * 1024 * 1024 * 1024
        if str(platform.system()).lower() == 'windows':
            import ctypes
            kernel32 = ctypes.windll.kernel32
            kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
        else:
            import resource
            resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))


def pre_check():
    if sys.version_info < (3, 9):
        quit('Python version is not supported - please upgrade to 3.9 or higher')
    if not shutil.which('ffmpeg'):
        quit('ffmpeg is not installed!')
    model_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../inswapper_128.onnx')
    if not os.path.isfile(model_path):
        quit('File "inswapper_128.onnx" does not exist!')
    if roop.globals.gpu_vendor == 'apple':
        if 'CoreMLExecutionProvider' not in roop.globals.providers:
            quit("You are using --gpu=apple flag but CoreML isn't available or properly installed on your system.")
    if roop.globals.gpu_vendor == 'amd':
        if 'ROCMExecutionProvider' not in roop.globals.providers:
            quit("You are using --gpu=amd flag but ROCM isn't available or properly installed on your system.")
    if roop.globals.gpu_vendor == 'nvidia':
        CUDA_VERSION = torch.version.cuda
        CUDNN_VERSION = torch.backends.cudnn.version()
        if not torch.cuda.is_available():
            quit("You are using --gpu=nvidia flag but CUDA isn't available or properly installed on your system.")
        if CUDA_VERSION > '11.8':
            quit(f"CUDA version {CUDA_VERSION} is not supported - please downgrade to 11.8")
        if CUDA_VERSION < '11.4':
            quit(f"CUDA version {CUDA_VERSION} is not supported - please upgrade to 11.8")
        if CUDNN_VERSION < 8220:
            quit(f"CUDNN version {CUDNN_VERSION} is not supported - please upgrade to 8.9.1")
        if CUDNN_VERSION > 8910:
            quit(f"CUDNN version {CUDNN_VERSION} is not supported - please downgrade to 8.9.1")


def get_video_frame(video_path, frame_number = 1):
    cap = cv2.VideoCapture(video_path)
    amount_of_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    cap.set(cv2.CAP_PROP_POS_FRAMES, min(amount_of_frames, frame_number-1))
    if not cap.isOpened():
        print("Error opening video file")
        return
    ret, frame = cap.read()
    if ret:
        return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    cap.release()


def preview_video(video_path):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print("Error opening video file")
        return 0
    amount_of_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    ret, frame = cap.read()
    if ret:
        frame = get_video_frame(video_path)

    cap.release()
    return (amount_of_frames, frame)


def status(string):
    value = "Status: " + string
    if 'cli_mode' in args:
        print(value)
    else:
        ui.update_status_label(value)


def process_video_multi_cores(source_img, frame_paths):
    n = len(frame_paths) // roop.globals.cpu_cores
    if n > 2:
        processes = []
        for i in range(0, len(frame_paths), n):
            p = POOL.apply_async(process_video, args=(source_img, frame_paths[i:i + n],))
            processes.append(p)
        for p in processes:
            p.get()
        POOL.close()
        POOL.join()



def select_face_handler(path: str):
    args.source_img = path


def select_target_handler(path: str):
    args.target_path = path
    return preview_video(args.target_path)


def toggle_all_faces_handler(value: int):
    roop.globals.all_faces = True if value == 1 else False


def toggle_fps_limit_handler(value: int):
    args.keep_fps = int(value != 1)


def toggle_keep_frames_handler(value: int):
    args.keep_frames = value


def save_file_handler(path: str):
    args.output_file = path


def create_test_preview(frame_number):
    return process_faces(
        get_face_single(cv2.imread(args.source_img)),
        get_video_frame(args.target_path, frame_number)
    )


app = Flask(__name__)
@app.route('/face_swap', methods=['POST'])
def face_swap():
    if request.method == 'POST':
        args.source_img=request.form.get('source_img')
        args.target_path = request.form.get('target_path')
        args.output_file = request.form.get('output_path')
        keep_fps = request.form.get('keep_fps')
        if keep_fps == '0':
            args.keep_fps = False
        else:
            args.keep_fps = True
        
        Keep_frames = request.form.get('Keep_frames')
        if Keep_frames == '0':
            args.Keep_frames = False
        else:
            args.Keep_frames = True

        all_faces = request.form.get('all_faces')
        if all_faces == '0':
            args.all_faces = False
        else:
            args.all_faces = True

    if not args.source_img or not os.path.isfile(args.source_img):
        print("\n[WARNING] Please select an image containing a face.")
        return
    elif not args.target_path or not os.path.isfile(args.target_path):
        print("\n[WARNING] Please select a video/image to swap face in.")
        return
    if not args.output_file:
        target_path = args.target_path
        args.output_file = rreplace(target_path, "/", "/swapped-", 1) if "/" in target_path else "swapped-" + target_path
    target_path = args.target_path
    test_face = get_face_single(cv2.imread(args.source_img))
    if not test_face:
        print("\n[WARNING] No face detected in source image. Please try with another one.\n")
        return
    if is_img(target_path):
        if predict_image(target_path) > 0.85:
            quit()
        process_img(args.source_img, target_path, args.output_file)
        # status("swap successful!")
        return 'ok'
    
    seconds, probabilities = predict_video_frames(video_path=args.target_path, frame_interval=100)
    if any(probability > 0.85 for probability in probabilities):
        quit()
    video_name_full = target_path.split("/")[-1]
    video_name = os.path.splitext(video_name_full)[0]
    output_dir = os.path.dirname(target_path) + "/" + video_name if os.path.dirname(target_path) else video_name
    Path(output_dir).mkdir(exist_ok=True)
    # status("detecting video's FPS...")
    fps, exact_fps = detect_fps(target_path)
    
    if not args.keep_fps and fps > 30:
        this_path = output_dir + "/" + video_name + ".mp4"
        set_fps(target_path, this_path, 30)
        target_path, exact_fps = this_path, 30
    else:
        shutil.copy(target_path, output_dir)
    # status("extracting frames...")
    extract_frames(target_path, output_dir)

    args.frame_paths = tuple(sorted(
        glob.glob(output_dir + "/*.png"),
        key=lambda x: int(x.split(sep)[-1].replace(".png", ""))
    ))

    # status("swapping in progress...")
    if roop.globals.gpu_vendor is None and roop.globals.cpu_cores > 1:
        global POOL
        POOL = mp.Pool(roop.globals.cpu_cores)
        process_video_multi_cores(args.source_img, args.frame_paths)
    else:
        process_video(args.source_img, args.frame_paths)
    # status("creating video...")
    create_video(video_name, exact_fps, output_dir)
    # status("adding audio...")
    add_audio(output_dir, target_path, video_name_full, args.keep_frames, args.output_file)
    save_path = args.output_file if args.output_file else output_dir + "/" + video_name + ".mp4"
    print("\n\nVideo saved as:", save_path, "\n\n")
    # status("swap successful!")

    return 'ok'

if __name__ == "__main__":
    print('Statrt server----------------')
    server = pywsgi.WSGIServer(('127.0.0.1', 5020), app)
    server.serve_forever()

9.客户端代码

import requests
import base64
import numpy as np
import cv2
import time

source_img = "z1.jpg" #要换的脸
target_path= "z2.mp4" #目标图像或者视频
output_path = "zface2.mp4" #保存的目录和文件名
keep_fps = '0' #视频,是否保持原帧率
Keep_frames = '0' 
all_faces = '0' #

data = {'source_img': source_img,'target_path' : target_path,'output_path':output_path,
        'keep-fps' : keep_fps,'Keep_frames':Keep_frames,'all_faces':all_faces}

resp = requests.post("http://127.0.0.1:5020/face_swap", data=data)
print(resp.content)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/689988.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

source-map定位生产问题

source-map 定位源码错误位置 需要安装source-map库webpack配置需要配上devtool: “hidden-source-map”&#xff0c;devtool详细配置看这里devtool配置配置完webpack打包后&#xff0c;可以看到打包出来的.js.map文件 将生产包产生错误的栈赋值给stack即可&#xff0c;即设置…

前端——原生HTML猫猫max桌宠(附源码)

一、前言 看见了max大佬和狗头人大佬做的一个桌宠&#xff0c;于是就像用web简单实现一下 二、代码包 https://wwwf.lanzout.com/iWfER0ze0cqd密码:fg88 三、简单效果 简单用了随机动作&#xff08;可以进行权重设置&#xff09; 四、踩坑情况 如果不是主循环loop里&#xff0…

记录--巧用 overflow-scroll 实现丝滑轮播图

这里给大家分享我在网上总结出来的一些知识&#xff0c;希望对大家有所帮助 前言: 近期我在项目中就接到了一个完成轮播图组件的需求。最开始我也像大家一样&#xff0c;直接选择使用了知名的开源项目 "Swiper"&#xff0c;但是后来发现它在移动端项目中某些测试环境…

Go的性能优化建议

前言&#xff1a; \textcolor{Green}{前言&#xff1a;} 前言&#xff1a; &#x1f49e;这个专栏就专门来记录一下寒假参加的第五期字节跳动训练营 &#x1f49e;从这个专栏里面可以迅速获得Go的知识 Go的性能优化建议 3 性能优化建议3.1 性能优化建议 - Benchmark3.2 性能优化…

一文解答危废行业信息化平台的必要性——哲讯智能科技

危险废物物联网监管系统可以通过物联网技术实现对危险废物的精准管理&#xff0c;不仅有利于提高危险废物管理水平&#xff0c;而且能够有效防范和减少重特大事故的发生&#xff0c;保障人民群众生命财产安全。利用物联网技术&#xff0c;通过传感器、无线网络、移动终端等设备…

linux CentOS 7下载步骤

1、官网地址&#xff1a;https://www.centos.org/download/ 2、 3、下载阿里云 4、下载 或minimal - 2009

08-购物车效果

先做数据&#xff0c;再做功能&#xff0c;最后界面 var goods [{pic: ./assets/g1.png,title: 椰云拿铁,desc: 1人份【年度重磅&#xff0c;一口吞云】√原创椰云topping&#xff0c;绵密轻盈到飞起&#xff01;原创瑞幸椰云™工艺&#xff0c;使用椰浆代替常规奶盖打造丰盈…

【SAS】【01】【scsi协议族】SCSI standards family

下图显示了SAM协议与SCSI协议族中其他协议标准和相关项目的关系。 SCSI Architecture Model: 定义SCSI系统模型、SCSI标准集的功能划分以及适用于所有SCSI实现和要求。Device-Type Specific Command Sets: 定义特定设备类型的实现标准&#xff0c;包括每种设备类型的设备模型。…

leetcode1884. 鸡蛋掉落-两枚鸡蛋.动态规划-java

鸡蛋掉落-两枚鸡蛋 leetcode1884. 鸡蛋掉落-两枚鸡蛋题目描述解题思路代码演示 动态规划代码演示 动态规划专题 leetcode1884. 鸡蛋掉落-两枚鸡蛋 来源&#xff1a;力扣&#xff08;LeetCode&#xff09; 链接&#xff1a;https://leetcode.cn/problems/egg-drop-with-2-eggs-a…

基于Python和Spacy的命名实体识别

命名实体识别&#xff08;Named Entity Recognition&#xff0c;简称NER&#xff09;是一种自然语言处理&#xff08;NLP&#xff09;方法&#xff0c;用于检测和分类文本中的命名实体&#xff0c;包括人物、组织、地点、日期、数量和其他可识别的现实世界实体。 Spacy是一个基…

STM32之HAL库微妙延迟(借助Systick)

代码 void bsp_us_delay(uint32_t us) {uint32_t start, now, delta, reload, us_tick;start SysTick->VAL;reload SysTick->LOAD;us_tick SystemCoreClock / 1000000UL;do {now SysTick->VAL;delta start > now ? start - now : reload start - now;} whi…

Element el-dropdown 事件

我这里是结合el-table一起使用 设置trigger"click" 就可以加点击事件 这里我需要点击下拉选择值后&#xff0c;既要得到下拉里面的值 也要得到这一行数据的值 重要的代码 <el-dropdowntrigger"click"command"handleCommand($event,scope.row,sc…

7 拓展中断_事件控制器(EXTI)

目录 EXTI-扩展中断和事件控制器 事件的概念 EXTI-扩展中断和事件控制器 EXTI外设框图 F1/F4/F7&#xff08;看懂与或门&#xff09; H7 STM32CubeMX中的EXTI配置 EXTI-扩展中断和事件控制器 事件的概念 STM32上许许多多的外设&#xff0c;是通过内部信号来协同工作的。…

VMware麒麟Kylin系统安装Linux

麒麟系统常用链接 https://www.jianshu.com/p/f58e2435b650 ios下载链接 https://eco.kylinos.cn/partners/mirror.html 其实基本上只有两个区别&#xff0c;一个是桌面操作系统和服务器操作系统的区别&#xff0c;一个是x86_64和arm内核的区别&#xff0c;我下的是这个海光版…

Splashtop 荣获2023年教育科技突破奖

2023年6月8日 加利福尼亚州库比蒂诺 Splashtop 在简化随处办公远程解决方案领域处于领先地位&#xff0c;该公司自豪地宣布其在教育科技突破奖评选活动中荣获“年度远程学习解决方案供应商奖”。这项在教育行业久负盛名的奖项特别关注创新性解决方案和创意公司&#xff0c;这些…

BlendOS 3 正在开发:承诺支持九个 Linux 发行版,无存储库更新

导读blendOS 发行版承诺混合 Arch Linux、Fedora Linux 和 Ubuntu&#xff0c;今年 4 月发布的 blendOS 2 使用 WayDroid&#xff0c;承诺运行 Android 应用程序。 开发商 Rudra Saraswat 表示&#xff0c;不可变发行版 blendOS 3 系统正在开发中&#xff0c;并承诺为不可变发行…

Nginx优化及防盗链

目录 一、隐藏版本号 1.查看版本号 2.修改配置文件 3.重启服务及查看版本号 二、修改用户 与组 1.修改配置文件 2.重启服务 三、缓存时间 1.修改配置文件 2.重启服务 3.测试访问 四、日志分割 1.写脚本 2.赋予执行权限并执行 3.验证 4.设置定时任务 五、连接超时 2…

ctfshow文件包含web87-117

1.web87 绕过死亡待可以使用rot13编码,还可以用base64编码,url两次编码&#xff0c;浏览器自动进行解码一次&#xff0c;代码解码一次&#xff0c;如果之编码一次&#xff0c;代码会被浏览器解码一次&#xff0c;这时候特殊字符还是url编码&#xff0c;而如php字符串则被还原&a…

扩增子高通量测序

扩增子测序是指利用合适的通用引物扩增环境中微生物的16S rDNA/18S rDNA /ITS高变区或功能基因&#xff0c;通过高通量测序技术检测PCR产物的序列变异和丰度信息&#xff0c;分析该环境下的微生物群落的多样性和分布规律&#xff0c;以揭示环境样品中微生物的种类、相对丰度、进…

人工智能数据集处理——数据清理2

目录 异常值的检测与处理 一、异常值的检测 1、使用3σ准则检测异常值 定义一个基于3σ准则检测的函数&#xff0c;使用该函数检测文件中的数据&#xff0c;并返回异常值 2、使用箱形图检测异常值 根据data.xlsx文件中的数据&#xff0c;使用boxplot()方法绘制一个箱型图 …