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

Python OpenCV:图像叠加后如何模糊整体内外边缘

解决鼻子图像叠加边缘生硬问题的方案

你的问题核心在于当前代码仅对轮廓线区域做模糊替换,未生成带羽化渐变的边缘mask,无法实现内外边缘的自然过渡。以下是修正后的解决方案:

核心思路

  1. 生成鼻子区域的硬边缘mask
  2. 对mask做高斯模糊,得到从鼻子内部(完全不透明)到外部(完全透明)的渐变羽化mask
  3. 通过软mask加权融合原始图像与模糊图像,实现边缘的平滑过渡

修正后的代码

import cv2
import numpy as np

def blur_image_edge(image: np.ndarray) -> np.ndarray:
    # 1. 生成鼻子区域的硬mask,优化噪点
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)
    # 形态学闭操作消除小噪点,让mask更完整
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    
    # 2. 生成羽化边缘的软mask,核大小决定过渡平缓程度
    blurred_mask = cv2.GaussianBlur(thresh, (51,51), 0)
    mask = blurred_mask / 255.0  # 归一化到0-1范围
    
    # 3. 对原始图像做全局模糊
    blurred_img = cv2.GaussianBlur(image, (21,21), 0)
    
    # 4. 加权融合:鼻子内部保留原图,边缘区域混合原图与模糊图,外部用模糊图
    result = (image * mask[..., np.newaxis]) + (blurred_img * (1 - mask[..., np.newaxis]))
    return result.astype(np.uint8)

关键改进点

  • 羽化软mask:替代原代码的硬轮廓mask,通过高斯模糊实现从鼻子到背景的渐变过渡,覆盖内外边缘区域
  • 加权融合:利用mask的渐变值让原图与模糊图平滑混合,避免生硬的边缘替换
  • mask优化:形态学操作消除mask噪点,确保鼻子区域的完整性

叠加到目标图像的补充建议

若要将处理后的鼻子叠加到人脸图像,直接用羽化mask做alpha混合:

def overlay_nose(face_img: np.ndarray, nose_img: np.ndarray, nose_x: int, nose_y: int) -> np.ndarray:
    processed_nose = blur_image_edge(nose_img)
    
    # 生成对应羽化mask
    gray_nose = cv2.cvtColor(nose_img, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray_nose, 60, 255, cv2.THRESH_BINARY)
    blurred_mask = cv2.GaussianBlur(thresh, (51,51), 0)
    mask = blurred_mask / 255.0
    
    # 定位人脸图像中的鼻子区域并做混合
    h, w = nose_img.shape[:2]
    roi = face_img[nose_y:nose_y+h, nose_x:nose_x+w]
    blended_roi = (roi * (1 - mask[..., np.newaxis])) + (processed_nose * mask[..., np.newaxis])
    face_img[nose_y:nose_y+h, nose_x:nose_x+w] = blended_roi.astype(np.uint8)
    
    return face_img

内容的提问来源于stack exchange,提问作者Михаил Морозов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:27