私的AI研究会 > SberSwap

個別の学習プロセス無しでFaceSwapを実現する:SberSwap

 個別の学習プロセス無しでFaceSwapを実現する「SberSwap」を検証する

※ 最終更新:2023/12/09 

サイト『SberSwapで、個別の学習プロセス無しでFaceSwapを実現する』 の検証]

概要

FaceSwapは、個別に学習プロセスが必要なため処理に時間がかかる。「SberSwap」は、個別の学習プロセス無しでFaceSwapを実現する

SberSwap モデル図

Google Colaboratory に実行環境を作成

  1. 上記サイト作者の デモサイト を開き「Open in Colab」① ボタンを押す

  2. 『FaceSwap』の Google Colab が開くので「ファイル」メニューから「ドライブにコピーを保存」を選択

  3. 『FaceSwap のコピー』のタイトルで開いた Google Colab のページで以降の操作を行う

  4. データファイルをダウンロードして解凍する(解凍した「update/work/SberSwap/」を使用する
     update_20231209.zip (115MB) <アップデート・データ>

環境設定

  1. 以下のセルを実行する ①(実行時間 2分)
    #@markdown #**セットアップ**
    
    # Clone github
    !git clone https://github.com/cedro3/sber-swap.git
    %cd sber-swap
    
    # load arcface
    !wget -P ./arcface_model https://github.com/sberbank-ai/sber-swap/releases/download/arcface/backbone.pth
    !wget -P ./arcface_model https://github.com/sberbank-ai/sber-swap/releases/download/arcface/iresnet.py
    
    # load landmarks detector
    !wget -P ./insightface_func/models/antelope https://github.com/sberbank-ai/sber-swap/releases/download/antelope/glintr100.onnx
    !wget -P ./insightface_func/models/antelope https://github.com/sberbank-ai/sber-swap/releases/download/antelope/scrfd_10g_bnkps.onnx
    
    # load model itself
    !wget -P ./weights https://github.com/sberbank-ai/sber-swap/releases/download/sber-swap-v2.0/G_unet_2blocks.pth
    
    # load super res model
    !wget -P ./weights https://github.com/sberbank-ai/sber-swap/releases/download/super-res/10_net_G.pth
    
    # Install required libraries
    !pip install mxnet-cu112
    !pip install onnxruntime-gpu==1.12
    !pip install insightface==0.2.1
    !pip install kornia==0.5.4
    !pip install dill
    
    !rm /usr/local/lib/python3.10/dist-packages/insightface/model_zoo/model_zoo.py #change the path to python in case you use a different version
    !wget -P /usr/local/lib/python3.10/dist-packages/insightface/model_zoo/ https://github.com/AlexanderGroshev/insightface/releases/download/model_zoo/model_zoo.py #change the path to python in case you use a different version
    
    # library import
    import cv2
    import torch
    import time
    import os
    from utils.inference.image_processing import crop_face, get_final_image, show_images
    from utils.inference.video_processing import read_video, get_target, get_final_video, add_audio_from_another_video, face_enhancement
    from utils.inference.core import model_inference
    from network.AEI_Net import AEI_Net
    from coordinate_reg.image_infer import Handler
    from insightface_func.face_detect_crop_multi import Face_detect_crop
    from arcface_model.iresnet import iresnet100
    from models.pix2pix_model import Pix2PixModel
    from models.config_sr import TestOptions
    
    
    # --- Initialize models ---
    app = Face_detect_crop(name='antelope', root='./insightface_func/models')
    app.prepare(ctx_id= 0, det_thresh=0.6, det_size=(640,640))
    
    # main model for generation
    G = AEI_Net(backbone='unet', num_blocks=2, c_id=512)
    G.eval()
    G.load_state_dict(torch.load('weights/G_unet_2blocks.pth', map_location=torch.device('cpu')))
    G = G.cuda()
    G = G.half()
    
    # arcface model to get face embedding
    netArc = iresnet100(fp16=False)
    netArc.load_state_dict(torch.load('arcface_model/backbone.pth'))
    netArc=netArc.cuda()
    netArc.eval()
    
    # model to get face landmarks
    handler = Handler('./coordinate_reg/model/2d106det', 0, ctx_id=0, det_size=640)
    
    # model to make superres of face, set use_sr=True if you want to use super resolution or use_sr=False if you don't
    use_sr = True
    if use_sr:
        os.environ['CUDA_VISIBLE_DEVICES'] = '0'
        torch.backends.cudnn.benchmark = True
        opt = TestOptions()
        #opt.which_epoch ='10_7'
        model = Pix2PixModel(opt)
        model.netG.train()
    ▼ - log - GoogleColab Tesla T4

  2. セルの実行終了② 後、左サイドバーの「ファイルボタン」を押す
    「sber-swap」③ の下に「examples」」④ フォルダがあることを確認する

顔画像を入れ替える

  1. 画像をFaceswap
    ・用意した画像を使用する場合は、「examples/images」フォルダへ、


    ・以下のセルを実行する(実行時間 7秒)
    #@title #**画像をFaceswap**
    #@markdown ・自分の画像は examples/images にアップロードして下さい
    source = '11.jpg' #@param {type:"string"}
    target = '45.jpg' #@param {type:"string"}
    source_path = 'examples/images/'+source
    target_path = 'examples/images/' + target
    
    source_full = cv2.imread(source_path)
    crop_size = 224 # don't change this
    batch_size =  40
    
    source = crop_face(source_full, app, crop_size)[0]
    source = [source[:, :, ::-1]]
    
    target_full = cv2.imread(target_path)
    full_frames = [target_full]
    target = get_target(full_frames, app, crop_size)
    
    final_frames_list, crop_frames_list, full_frames, tfm_array_list = model_inference(full_frames,source,target,netArc,G,app,set_target = False,crop_size=crop_size,BS=batch_size)
    
    result = get_final_image(final_frames_list, crop_frames_list, full_frames[0], tfm_array_list, handler)
    cv2.imwrite('examples/results/result.png', result)
    ▼ - log - GoogleColab Tesla T4

  2. 画像を表示する

    ・以下のセルを実行する(実行時間 7秒)
    #@markdown #**画像を表示**
    #@markdown ・画像は examples/results/results.png に保存されています
    import matplotlib.pyplot as plt
    
    show_images([source[0][:, :, ::-1], target_full, result], ['Source Image', 'Target Image', 'Swapped Image'], figsize=(20, 15))

動画の顔を入れ替える

  1. 動画をFaceswap
    ・動画ファイル指定

  2. Style transfer を実行し動画を作成
    ・以下のセルを実行する(実行時間 2分)
    #@title #**動画をFaceswap**
    #@markdown ・自分の画像は examples/images にアップロードして下さい\
    #@markdown ・自分の動画は examples/videos にアップロードして下さい
    source = '45.jpg' #@param {type:"string"}
    video = 'kao_cm1.mp4' #@param {type:"string"}
    source_path = 'examples/images/'+source
    path_to_video = 'examples/videos/'+video
    
    source_full = cv2.imread(source_path)
    OUT_VIDEO_NAME = "examples/results/result.mp4"
    crop_size = 224 # don't change this
    batch_size =  40
    
    source = crop_face(source_full, app, crop_size)[0]
    source = [source[:, :, ::-1]]
    
    full_frames, fps = read_video(path_to_video)
    target = get_target(full_frames, app, crop_size)
    
    START_TIME = time.time()
    
    final_frames_list, crop_frames_list, full_frames, tfm_array_list = model_inference(full_frames,source,target,netArc,G,app,set_target = False,crop_size=crop_size,BS=batch_size)
    
    if use_sr:
        final_frames_list = face_enhancement(final_frames_list, model)
    
    get_final_video(final_frames_list,crop_frames_list,full_frames,tfm_array_list,OUT_VIDEO_NAME,fps,handler)
    
    add_audio_from_another_video(path_to_video, OUT_VIDEO_NAME, "audio")
    
    print(f'Full pipeline took {time.time() - START_TIME}')
    print(f"Video saved with path {OUT_VIDEO_NAME}")
    ▼ - log - GoogleColab Tesla T4

  3. 動画の再生
    ・以下のセルを実行する
    #@markdown #**動画を表示**
    #@markdown ・動画は examples/results/results.mp4 に保存されています
    from IPython.display import HTML
    from base64 import b64encode
    
    video_file = open(OUT_VIDEO_NAME, "r+b").read()
    video_url = f"data:video/mp4;base64,{b64encode(video_file).decode()}"
    
    HTML(f"""<video width={800} controls><source src="{video_url}"></video>""")
     
    ・元画像 (オリジナル動画 / Terget 顔画像)
     

SberSwap 実行例

・静止画

編集の終了・再接続後の実行

  1. 編集を終えるときは Colab「ランタイム」→「ランタイムを接続解除して削除」を選択する
    ・GPU 占有時間を少なくするためすべての実行作業が終了した場合は接続解除しておくことが望ましい
    ・接続解除して削除を実行しても、ノートブック上の実行結果はそのまま残る

  2. 再接続の場合は上記の 環境設定 からもう一度実行同じ手順をする

更新履歴

参考資料

 

Last-modified: 2023-12-09 (土) 04:58:10