You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenCV和Python调整人脸眼睛、鼻子大小并导出保存图像

鼻子大小调整实现方案

实现逻辑

  • 利用dlib 68点人脸关键点定位提取鼻子区域的9个特征点(索引范围27~35,覆盖鼻梁、鼻翼、鼻尖全区域)
  • 计算鼻子区域的外接边界框,裁剪原图像中的鼻子区域
  • 按自定义缩放系数调整鼻子区域的尺寸
  • 通过OpenCV泊松无缝融合能力,将调整后的鼻子区域贴合回原图像,避免出现生硬的拼接边界
  • 最终导出保存调整后的图像

完整可运行代码

import cv2
import numpy as np
import dlib

# 读取并预处理输入图像
img = cv2.imread('1.jpg')
img = cv2.resize(img, (0,0), None, 0.5, 0.5)
imgOriginal = img.copy()

# 加载dlib人脸检测和关键点检测模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(imgGray)

for face in faces:
    x1, y1 = face.left(), face.top()
    x2, y2 = face.right(), face.bottom()
    landmarks = predictor(imgGray, face)
    myPoints = []
    for n in range(68):
        x = landmarks.part(n).x
        y = landmarks.part(n).y
        myPoints.append([x, y])
    myPoints = np.array(myPoints)
    
    # 提取鼻子区域关键点,68点中索引27-35对应鼻子区域
    nose_points = myPoints[27:36]
    # 计算鼻子外接边界框
    x, y, w, h = cv2.boundingRect(nose_points)
    # 鼻子缩放系数:>1为放大,<1为缩小,可根据需求调整
    nose_scale = 1.2
    # 计算缩放后的鼻子尺寸
    new_w = int(w * nose_scale)
    new_h = int(h * nose_scale)
    
    # 裁剪原鼻子区域并缩放
    nose_roi = img[y:y+h, x:x+w]
    resized_nose = cv2.resize(nose_roi, (new_w, new_h), interpolation=cv2.INTER_CUBIC)
    
    # 生成鼻子掩膜,用于无缝融合
    nose_mask = np.zeros((h, w), dtype=np.uint8)
    cv2.fillConvexPoly(nose_mask, nose_points - np.array([x, y]), 255)
    resized_mask = cv2.resize(nose_mask, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
    
    # 计算缩放后鼻子的放置中心,和原鼻子中心对齐,避免位置偏移
    center_x = x + w // 2
    center_y = y + h // 2
    
    # 泊松无缝融合,将调整后的鼻子贴回原图
    imgOriginal = cv2.seamlessClone(resized_nose, imgOriginal, resized_mask, (center_x, center_y), cv2.NORMAL_CLONE)

# 保存调整后的图像
cv2.imwrite('adjusted_nose.jpg', imgOriginal)
# 显示结果
cv2.imshow('调整后效果', imgOriginal)
cv2.waitKey(0)
cv2.destroyAllWindows()

参数说明

  • 调整nose_scale参数即可修改鼻子大小:设置为1.2代表放大20%,设置为0.8代表缩小20%
  • 若需要更精准的鼻子区域调整,可自行修改鼻子关键点的索引范围

内容的提问来源于stack exchange,提问作者mahsa nemati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:36:06