python常用代码块 | python 人脸识别(腾讯 gfpgan方案)

python 人脸识别(腾讯 gfpgan方案)

实现功能

使用腾讯 gfpgan方案进行人脸识别并高清修复

1.首先在github下载源文件https://github.com/TencentARC/GFPGAN

左边是从视频中截取的人脸,右边是修复后的结果,只能说这效果杠杠的
在这里插入图片描述
2.代码修改后,运行时会在’xxx\gfpgan\weights’文件夹中自动下载GFPGANv1.3.pth
模型文件,同时在程序的文件夹’xxx\notepad\gfpgan\weights’下会下载’detection_Resnet50_Final.pth’, ‘parsing_parsenet.pth’两个模型,
可以自动运行时自动下载相应模型到对应位置,
也可以在如下链接’ ’下载这三个模型,然后放到对应的文件夹下
gfpgan项目放置到自己项目目录即可
自动下载的模型
自动下载的模型

核心代码分三步:
1)定义关键参数(未做修改)
upscale = 2
arch ='clean'
channel_multiplier=2
bg_upsampler = None
aligned = False
only_center_face = False
weight=0.5

2)调用GFPGANer(...)
restorer = GFPGANer(
    model_path=model_path,
    upscale=upscale,
    arch=arch,
    channel_multiplier=channel_multiplier,
    bg_upsampler=bg_upsampler)

3)
cropped_faces, restored_faces, restored_img = restorer.enhance(
            input_img,
            has_aligned=aligned,
            only_center_face=only_center_face,
            paste_back=True,
            weight=weight)
---restored_faces即是我们需要的图片数据
完整代码如下:

from gfpgan import GFPGANer
import torch,os,glob,cv2,sys
import numpy as np
#from basicsr.utils import imwrite

baseDirPath = sys.path[0]
print(baseDirPath)

###################################################################
#读含中文/韩文/日文等特殊字符路径的图片
def cv_imread(in_path):
  im = cv2.imdecode(np.fromfile(in_path, dtype=np.uint8),-1)
  return im
  
#路径中有中文名 cv2写
def cv_imwrite(out_path, imp_np):
  imp_type = '.' + out_path.split('.')[-1]
  cv2.imencode(imp_type, imp_np)[1].tofile(out_path)
###################################################################

#模型位置
model_path = baseDirPath + '\\gfpgan\\weights\\GFPGANv1.3.pth'

#如下参数固定不变
upscale = 2
arch ='clean'
channel_multiplier=2
bg_upsampler = None
aligned = False
only_center_face = False
weight=0.5

if not torch.cuda.is_available():  # CPU
    bg_upsampler = None

restorer = GFPGANer(
    model_path=model_path,
    upscale=upscale,
    arch=arch,
    channel_multiplier=channel_multiplier,
    bg_upsampler=bg_upsampler)

input_path = baseDirPath + '\\pic\\src'
output_path = baseDirPath + '\\pic\\dst'

if os.path.isfile(input_path):
    img_list = [input_path]
else:
    img_list = sorted(glob.glob(os.path.join(input_path, '*')))
print(img_list)

for img_path in img_list:
    img_name = os.path.basename(img_path)
    
    print(f'processing {img_name} ...')
    basename, ext = os.path.splitext(img_name)
    
    input_img = cv_imread(img_path)
    
    cropped_faces, restored_faces, restored_img = restorer.enhance(
            input_img,
            has_aligned=aligned,
            only_center_face=only_center_face,
            paste_back=True,
            weight=weight)
    
    # save faces
    for idx, restored_face in enumerate(restored_faces):
        # save restored face
        save_restore_path = os.path.join(output_path,  f'{basename}_{idx:02d}.png')
        cv_imwrite(save_restore_path, restored_face)

print(f'Results are in the [{output_path}] folder.')

备注:如果输入图片尺寸较小或质量较差,会出现很多奇葩结果,如这样:
在这里插入图片描述

源码:https://download.csdn.net/download/mjc1321/89070575

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Python实现LDA人脸识别的示例代码: ```python import cv2 import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA # 读取人脸图像并进行预处理 def preprocess_image(image_path): image = cv2.imread(image_path) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5) for (x, y, w, h) in faces: face = gray[y:y+h, x:x+w] face = cv2.resize(face, (100, 100)) return face.flatten() # 获取人脸数据和标签 def get_data(): data = [] labels = [] for i in range(1, 11): for j in range(1, 6): image_path = f"person{i}/{j}.jpg" label = i face = preprocess_image(image_path) data.append(face) labels.append(label) return np.array(data), np.array(labels) # 训练LDA模型并返回模型和均值向量 def train_lda(data, labels): lda = LDA() lda.fit(data, labels) return lda, lda.means_ # 预测人脸图像的标签 def predict(lda, means, image_path): face = preprocess_image(image_path) face = face.reshape(1, -1) face -= means prediction = lda.predict(face) return prediction[0] # 测试LDA人脸识别 data, labels = get_data() lda, means = train_lda(data, labels) test_image_path = "test.jpg" prediction = predict(lda, means, test_image_path) print(f"The predicted label is {prediction}") ``` 在上述示例代码中,`preprocess_image`函数用于读取人脸图像并进行预处理,包括灰度化、裁剪、缩放等操作。`get_data`函数用于获取人脸数据和标签,其中包括10个人的50张人脸图像。`train_lda`函数用于训练LDA模型,并返回模型和均值向量。`predict`函数用于预测人脸图像的标签。最后,通过调用`get_data`、`train_lda`和`predict`函数来测试LDA人脸识别的准确率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值