首页 > 其他分享 >关于 ModelScope 的视频 “AI 换脸” 优化方案

关于 ModelScope 的视频 “AI 换脸” 优化方案

时间:2023-04-18 11:33:05浏览次数:31  
标签:img AI os ModelScope filename import path face 换脸

前言

        前面一文,初步完成了一下 “AI 换脸” 视频处理程序。完成了视频拆帧,拆帧图片人脸融合,已经音频提取和最后的人脸融合图片的整合(也就是将图片和音频组成视频)。但是在人脸融合部分由于是单线程,处理起来非常耗时,所以这里就对那部分进行优化。

 

优化前情况

        "敏捷开发,快速迭代",好像这种思维从多年前就埋在了脑子里 (借口)。所以前文算是个初版 demo,并且在环境中运行只是用 cmd 来完成,没有使用专门 Python 的 IDE。也很有可能是这个原因,在执行代码里,只要是关于获取当前目录的地方都不起效果,这是一点另一点就是上面重点要解决的,提升人脸替换的处理速度,这里要用到多线程。

 

编码

1. 人脸替换部分

用法就不多讲了,Py 相关的文档有讲,以下只是代码片段,可以用这个替换前面文章代码里的 face_replace 函数。经过测试,相同的张数的图片 (这里只有 403 张),处理时间比前者缩短了半小时。

def face_replace(user_path=""):
    import threading
    from pathlib import Path

    import cv2
    from modelscope.outputs import OutputKeys
    from modelscope.pipelines import pipeline
    from modelscope.utils.constant import Tasks
    import os
    os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

    max_workers = 2
    semaphore = threading.Semaphore(max_workers)

    def my_function(img_path):

        with semaphore:
            print(f"{img_path}  开始")
            image_face_fusion = pipeline(Tasks.image_face_fusion,
                                         model='damo/cv_unet-image-face-fusion_damo')
            template_path = img_path
            filename = os.path.splitext(os.path.basename(img_path))[0]

            result = image_face_fusion(dict(template=template_path, user=user_path))
            cv2.imwrite(f'video_imgout/{filename}.jpg', result[OutputKeys.OUTPUT_IMG])
            print(f"{filename}.png ok")

    threads = []
    BASE_PATH = os.path.dirname(__file__)
    for dirpath, dirnames, filenames in os.walk(BASE_PATH + "/video_img"):
        for filename in filenames:
            print(filename)
            if filename.endswith('.jpg'):
                file_path = Path(os.path.join(dirpath, filename))
                t = threading.Thread(target=my_function, args=(str(file_path),)).start()
                threads.append(t)

 

pycharm 部分

        由于也有一些没有接触过 python 的小伙伴留言,这里就再介绍一下 IDE 的运行,也为了解决在 cmd 中运行出现获取当前路径问题。前面也有文章介绍关于 Python 虚拟环境的创建,这里就跳过了,直接演示在 IDE 中配置虚拟环境和运行代码。

1. 查看当前环境下的环境列表。

2. 打开 IDE 创建项目后进入。

3. 选择 Project,选择已经创建好的虚拟环境。

4. 查看当前项目是否在该环境下

5. 最后就可以直接用于代码了。

 

标签:img,AI,os,ModelScope,filename,import,path,face,换脸
From: https://www.cnblogs.com/zerofc/p/17328972.html

相关文章

  • Fabarta 获过亿元人民币 Pre-A 轮融资,打造面向 AI 的图智能 Infra
    4月18日,图智能公司Fabarta宣布已经成功获得亿元人民币的Pre-A轮融资。本轮融资由朗玛峰创投领投,蓝驰创投、将门创投跟投。据悉,在过去一年内Fabarta连续完成两轮数亿元融资,蓝驰创投为2022年初Fabarta天使轮领投方,将门创投和加盛巢生资本跟投。蓝驰创投和将门创投作为......
  • Oracle等待事件(二)—— free buffer wait 常见原因及对应解决方法
    首先看看官方文档中的描述Thiswaiteventindicatesthataserverprocesswasunabletofindafreebufferandhaspostedthedatabasewritertomakefreebuffersbywritingoutdirtybuffers.Adirtybufferisabufferwhosecontentshavebeenmodified.Dirtyb......
  • 《Ubuntu — NetworkManager开机提示A start job is running for Network Manager wai
    轉自:https://www.cnblogs.com/zhuangquan/p/13209758.html,僅供參考學習使用1.NetworkManagerUbuntuServer:Ubuntu的Server版本只有终端界面,没有桌面GUI,且Server版本不会安装NetworkManager,所以UbuntuServer网络由配置文件进行配置。由于Server版本一般用作服务器的......
  • Failover and Failover Modes (Always On Availability Groups)
    一、HowAutomaticFailoverWorks 自动故障转移的工作方式Iftheserverinstancethatishostingthecurrentprimaryreplicaisstillrunning,itchangesthestateoftheprimarydatabasestoDISCONNECTEDanddisconnectsallclients.关闭主库,断开所有客户端连接I......
  • ziyi-lstm-train代码
    lstm的train代码deftrain_lstm(net,lr,train_loader,total_epoch):global_step=1optimizer=torch.optim.Adam(net.parameters(),lr=lr)scheduler=lr_scheduler.MultiStepLR(optimizer,milestones=[iforiinrange(0,500,150)][1:],gamma=0.05)......
  • JavaScript 利用 async await 实现 sleep 效果
    constsleep=(timeountMS)=>newPromise((resolve)=>{setTimeout(resolve,timeountMS);});(async()=>{console.log('11111111,'+newDate());awaitsleep(2000);console.log('22222222,'+newDate());await......
  • ArcPy 批处理之 [ hdf转tif ]; [ Con函数 ]; 镶嵌至新栅格 [ Mosaic to New Raster ];
    一、 ArcPy批量将文件夹内的*.hdf文件转为*.tif 文件:#encoding:utf-8 ##hdf2tifimportarcpyimportosinPath=r'E:\Data\S00_DataHdf\\'outPath=r'E:\Data\S01_DataTif\\'fordirpath,dirnames,filenamesinos.walk(inPath):......
  • Add Again UVA - 11076
     defineS,itissumofallpossiblepermutationsofagivensetofdigits.Forexample,ifthedigitsare<123>,thensixpossiblepermutationsare<123>,<132>,<213>,<231>,<312>,<321>andthesumofthemis......
  • retain和release
    如果继承自cc.Class或其子类,那么jsb就引用了c++的内存。这样就可能用到retain和release如果不调用c++层的方法,那么没必要用retain和release因为c++层的内存和js层是独立管理的。比如ClassA=cc.Layer.extend(...);如果不调用和c++层的layer相关的函数或属性【比如addChild】,就......
  • AI在金融体系下如何引导API安全?
    AI在金融体系下如何引导API安全?随着金融科技的快速发展,越来越多的金融机构开始使用API(应用程序接口)进行数字化转型,加速业务流程和数据交换。然而,API在金融体系下面临诸多安全威胁,如恶意攻击、数据泄露等,这些安全问题可能会导致金融风险和市场失信。为了保障金融API的安全性,可以采......