音视频开发之旅(71)- 人脸修复画质增强之GFPGAN

本文详细解析了GFPGAN的工作原理,包括其结构、loss函数和代码实现,同时比较了GFPGAN与CodeFormer在人脸图像恢复方面的优劣。介绍了如何在SDWebui中集成GFPGAN,并讨论了两者在不同场景下的适用性。
摘要由CSDN通过智能技术生成

目录

1. 效果展示

2. GFPGAN原理浅析和代码实现分析

3. SDWebui中使用

4. GFPGAN和CodeFormer对比

5. 参考资料

一、效果展示

图片

图片

二、GFPGAN原理浅析和代码实现分析

图片

图片来源:https://arxiv.org/pdf/2101.04061.pdf

2.1 GFP-GAN框架概述

它由一个U-Net模块和一个预训练的人脸GAN模型组成。

GFP-GAN中为了保证人脸变清晰同时保持真实性,有四个loss

1. “Reconstruction Loss” 使用预训练的 VGG-19 网络来完成分辨率的增强

2. “Adversarial Loss” 使用 StyleGAN2 中类似的方法来生成逼真的纹理;

3. “Facial Component Loss” 为了让面部细节真实,使用辨别器单独生成和应用面部区块的补丁,特别处理了眼睛、嘴巴等局部细节;

4. “Identity Preserving Loss” 使用预训练的 ArcFace 模型,来帮助将原始图片中的身份特征恢复到 GFPGAN 生成的新图片中。

2.2 代码实现分析

2.2.1 模型加载

模型加载方面和CodeFormer基本一致:人脸检测模型retinaface_resnet50、背景超分模型realesrgan;以及人脸修复的GFPGAN模型

inference_gfpgan.py### 设置背景超分RealEsrGAN模型if args.bg_upsampler == 'realesrgan':    from basicsr.archs.rrdbnet_arch import RRDBNet    from realesrgan import RealESRGANer    model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)    bg_upsampler = RealESRGANer(        scale=2,        model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth',        model=model,        tile=args.bg_tile,        tile_pad=10,        pre_pad=0,        half=True)  # need to set False in CPU mode

####  设置GFPGAN模型arch = 'clean'channel_multiplier = 2model_name = 'GFPGANv1.4'url = 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth'
model_path = os.path.join('experiments/pretrained_models', model_name + '.pth')restorer = GFPGANer(    model_path=model_path,    upscale=args.upscale,    arch=arch,    channel_multiplier=channel_multiplier,    bg_upsampler=bg_upsampler)        #gfpgan/utils.py 初始化人脸修复helper类(使用retinaface_resnet50模型) 提供人脸关键点检测、人脸裁剪对齐以及贴合原图等功能封装self.face_helper = FaceRestoreHelper(            upscale,            face_size=512,            crop_ratio=(1, 1),            det_model='retinaface_resnet50',            save_ext='png',            use_parse=True,            device=self.device,            model_rootpath='gfpgan/weights')

2.2.2 人脸修复

可以看到处理流程和CodeFormer完全一致:获取人脸5个关键点、对人脸进行摆正裁剪、进行人脸修复 最后把修复后的人脸贴回原图

​​​​​​​

input_img = cv2.imread(img_path, cv2.IMREAD_COLOR)#返回人脸裁剪后图片cropped_faces;人脸修复后图片restored_faces以及人脸修复后贴回原图的图片restored_imgcropped_faces, restored_faces, restored_img = restorer.enhance(    input_img,    has_aligned=args.aligned,    only_center_face=args.only_center_face,    paste_back=True,    weight=args.weight)

restorer.enhance的实现在gfpgan/utils.py

​​​​​​​

self.face_helper.read_image(img)# 获取每个人脸的5个关键点self.face_helper.get_face_landmarks_5(only_center_face=only_center_face, eye_dist_threshold=5)#对人人脸进行摆正和裁剪处理self.face_helper.align_warp_face()
#对人脸进行修复for cropped_face in self.face_helper.cropped_faces:    # prepare data    cropped_face_t = img2tensor(cropped_face / 255., bgr2rgb=True, float32=True)    normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)    cropped_face_t = cropped_face_t.unsqueeze(0).to(self.device)
    try:        output = self.gfpgan(cropped_face_t, return_rgb=False, weight=weight)[0]        # convert to image        restored_face = tensor2img(output.squeeze(0), rgb2bgr=True, min_max=(-1, 1))    except RuntimeError as error:        print(f'\tFailed inference for GFPGAN: {error}.')        restored_face = cropped_face
    restored_face = restored_face.astype('uint8')    self.face_helper.add_restored_face(restored_face)    #把修复后的人脸贴回原图    if not has_aligned and paste_back:    # upsample the background    if self.bg_upsampler is not None:        # Now only support RealESRGAN for upsampling background        bg_img = self.bg_upsampler.enhance(img, outscale=self.upscale)[0]    else:        bg_img = None
    self.face_helper.get_inverse_affine(None)    # paste each restored face to the input image    restored_img = self.face_helper.paste_faces_to_input_image(upsample_img=bg_img)    return self.face_helper.cropped_faces, self.face_helper.restored_faces, restored_img

三、SDWebui中使用

图片

代码实现在 modules/gfpgan_model.py

#加载模型model_url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth"models = modelloader.load_models(model_path, model_url, user_path, ext_filter="GFPGAN")
#人脸修复cropped_faces, restored_faces, gfpgan_output_bgr = model.enhance(np_image_bgr, has_aligned=False, onl

四、GFPGAN和CodeFormer对比

GFP-GAN在处理严重退化和保持面部身份方面表现出色,适合于高质量人脸图像恢复。CodeFormer通过利用Transformer技术提供更自然的面部细节恢复,适合于要求高自然度和面部表情复原的应用

选择什么模型,结合自己的实际情况,如果需求对人脸还原保真度要求比较高,gfpgan效果稍微好点;如果追求更锐化的效果 可以使用CodeFormer。

当然每个算法模型都不是完美的,都会有badcase存在,比如下图中的舌头部分。

算法不能完全完美自动化时,人工审核还是有必要的

图片

五、参考资料

1. GFPGAN论文  https://arxiv.org/abs/2101.04061

2.GFPGAN(论文简述)https://www.bilibili.com/video/BV1Hr4y1C7vK/?spm_id_from=333.337.search-card.all.click&vd_source=03a763fa6cf49b01f658f32592f5a6f3

3. Stable Diffusion 硬核生存指南:WebUI 中的 GFPGAN https://soulteary.com/2023/08/04/stable-diffusion-hardcore-survival-guide-gfpgan-in-webui.html

4. 人脸修复画质增强之CodeFormer https://mp.weixin.qq.com/s?__biz=MzU5NjkxMjE5Mg==&mid=2247484778&idx=1&sn=0153e357b05dc9e46a35e92741df45da&chksm=fe5a3445c92dbd5308862f509d13bdbb0e5b209591c2abc68e7ac394e9f0cd7b44df388b46fd&token=548063262&lang=zh_CN&poc_token=HDpE3WWj5jIP0kPTpGTftRwu52iXp0H2JEnLtu18

感谢你的阅读

接下来我们继续学习输出AIGC相关内容,欢迎关注公众号“音视频开发之旅”,一起学习成长。

欢迎交流

  • 10
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值