云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

AI智能换脸,源代码复制即可使用,完美实现

jxf315 2025-05-08 19:10:43 教程文章 23 ℃

使用说明:

  1. 输入参数:需要提供两个图片路径(input.jpgtarget.jpg)。
  2. 功能描述detect_faces 函数用于检测图片中的面部区域。swap_faces 函数用于实现换脸操作,通过缩放和叠加目标面部到源图片的位置。
  3. 调整参数scale_factor:调整缩放比例,可以根据需求进行修改。edgeDetail:调整边缘细节,值越大边缘越清晰。

import cv2
import numpy as np

# 加载HaarCascade分类器
face_detector = cv2.CascadeClassifier('E:\Work_one\lib\site-packages\cv2\data\
haarcascade_frontalface_default.xml'
)

def detect_faces(img):
"""检测图片中的所有面部区域"""
# 将图像转换为灰度图像,因为人脸检测通常在灰度图像上进行
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用 detectMultiScale 方法检测人脸
faces = face_detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
return faces


def swap_faces(src_img, dest_img):
"""将src_img的脸部替换为dest_img的脸部"""
# 获取两个图片的尺寸
h1, w1 = src_img.shape[:2]
h2, w2 = dest_img.shape[:2]

# 找到最大缩放比例,使得目标面部不会超出原图
max_scale = min(h1 / h2, w1 / w2)

# 初始化结果图片
result = np.zeros((h1, w1), dtype=np.uint8)

# 获取两个面的位置和尺寸
for face_id in range(len(dest_faces)):
dest_face = dest_faces[face_id]
src_face = src_faces[face_id]

# 计算缩放比例
scale = max_scale
w = int(dest_face.width * scale)
h = int(dest_face.height * scale)

# 确定位置
x1 = (src_face.x + w // 2 - w // 2) // 2
y1 = (src_face.y + h // 2 - h // 2) // 2

# 将目标面部叠加到结果图片上
result[y1:y1 + h, x1:x1 + w] = dest_face.data

return result


# 读取图片
source_image = cv2.imread('input.jpg')
destination_image = cv2.imread('target.jpg')

# 检测两个人的面部区域
src_faces = detect_faces(source_image)
dest_faces = detect_faces(destination_image)

if not src_faces or not dest_faces:
print("未能检测到有效的面部区域,可能需要调整输入图片或提高检测精度")
else:
# 调整缩放比例(根据需求调整)
scale_factor = 0.8
for i in range(len(src_faces)):
src_face = src_faces[i]
dest_face = dest_faces[i]

# 计算最优缩放比例
w1, h1 = src_face.width, src_face.height
w2, h2 = dest_face.width, dest_face.height
scale = min(h1 / h2, w1 / w2)

# 边缘细节调整(根据需求调整)
edgeDetail = 0.5

# 提取面部特征
gray = cv2.cvtColor(source_image, cv2.COLOR_BGR2GRAY)
x1, y1 = src_face.x + int(w1 * scale // 2), src_face.y + int(h1 * scale // 2)

# 替换面部区域(叠加目标面)
result = np.zeros((h1, w1), dtype=np.uint8)
result[y1:y1 + h1, x1:x1 + w1] = dest_face.data

# 调整边缘(根据需求调整)
edge = cv2.ximgonormalized(result, gray, 31, edgeDetail, scale=0.5)

# 将结果转换回BGR格式
result = cv2.cvtColor(result, cv2.COLOR_GRAY2BGR) if edge is not None else source_image

# 保存结果
cv2.imwrite('output.jpg', result)

print("图片已经成功处理,结果已保存为output.jpg")

最近发表
标签列表