如何在Python中为图像特定区域应用类Photoshop液化的Bulge效果?
Python实现图像局部Bulge膨胀效果(类似PS液化工具)
基于你提到的全图Bulge算法,只需添加区域蒙版限制,就能实现局部(比如眼睛)的膨胀效果。核心逻辑是:仅对指定中心和半径范围内的像素应用Bulge变换,区域外像素保持原始状态。
完整实现代码
import cv2 import numpy as np def local_bulge_effect(img, center_x, center_y, radius, strength=0.5): # 获取图像尺寸 h, w = img.shape[:2] # 创建与原图同尺寸的输出图像,初始复制原图 output = img.copy() # 创建蒙版:仅保留指定半径内的区域 mask = np.zeros((h, w), dtype=np.uint8) cv2.circle(mask, (center_x, center_y), radius, 255, -1) # 遍历蒙版内的每个像素 for y in range(h): for x in range(w): if mask[y, x] == 255: # 计算当前像素到中心的相对坐标 dx = x - center_x dy = y - center_y distance = np.sqrt(dx**2 + dy**2) if distance < radius: # 计算膨胀后的偏移量(基于全图算法修改) ratio = (radius - distance) / radius theta = np.arctan2(dy, dx) new_distance = distance * (1 - strength * ratio) # 计算新坐标 new_x = int(center_x + new_distance * np.cos(theta)) new_y = int(center_y + new_distance * np.sin(theta)) # 确保新坐标在图像范围内 new_x = np.clip(new_x, 0, w-1) new_y = np.clip(new_y, 0, h-1) # 赋值变换后的像素 output[y, x] = img[new_y, new_x] return output # 使用示例:放大眼睛 if __name__ == "__main__": # 读取图像 img = cv2.imread("your_image.jpg") # 假设左眼中心坐标为(200, 300),半径50,强度0.6 result = local_bulge_effect(img, 200, 300, 50, 0.6) # 右眼同理 result = local_bulge_effect(result, 350, 300, 50, 0.6) # 保存或显示结果 cv2.imwrite("bulge_eyes.jpg", result) cv2.imshow("Local Bulge Effect", result) cv2.waitKey(0) cv2.destroyAllWindows()
关键细节说明
- 蒙版创建:用
cv2.circle生成圆形蒙版,精准限定需要处理的区域,你也可以根据需求改成矩形、椭圆或自定义形状的蒙版。 - 强度参数:
strength取值范围0~1,值越大膨胀效果越明显,超过1可能出现过度变形。 - 坐标处理:对变换后的坐标做
np.clip限制,避免出现越界报错。 - 效率优化:如果处理大图像,可改用numpy向量运算替代双重循环,提升运行速度。
内容的提问来源于stack exchange,提问作者Mr Pixel
相关产品推荐
相关产品推荐

