File size: 2,319 Bytes
28ea85c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | import numpy as np
from PIL import Image
import torch
import cv2
def numpy2tensor(image: Image.Image):
return torch.from_numpy(image).unsqueeze(0)
class LightColorCulling:
@classmethod
def INPUT_TYPES(self):
return {
"required": {
"image": ("IMAGE",),
"white_threshold": ("FLOAT", {"default": 0.7, "min": 0.0, "max": 0.9, "step": 0.01}),
"transition_range": ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE", )
RETURN_NAMES = ("image", )
FUNCTION = 'Preprocessing'
CATEGORY = 'StickerEdit/LightColorCulling'
def Preprocessing(self, image, white_threshold=0.7, transition_range=0.2):
image_np = (image.cpu().numpy().squeeze()*255).astype(np.uint8)
# 检查图像是否有透明通道
has_alpha = image_np.shape[2] == 4
# 转换为灰度图
gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
# 归一化灰度图像到0-1范围
normalized_gray = gray / 255.0
# 创建结果图像
result_image = image_np.copy()
# 创建透明度通道
if has_alpha:
b_channel, g_channel, r_channel, alpha_channel = cv2.split(result_image)
else:
alpha_channel = np.ones_like(gray, dtype=float) * 255
b_channel, g_channel, r_channel = cv2.split(result_image)
# 计算渐变透明度
mask = normalized_gray >= white_threshold
transition_mask = (normalized_gray >= (white_threshold - transition_range)) & (normalized_gray < white_threshold)
alpha_channel[mask] = 0
alpha_channel[transition_mask] = (1 - (normalized_gray[transition_mask] - (white_threshold - transition_range)) / transition_range) * 255
# 更新结果图像的alpha通道
# import pdb;pdb.set_trace()
result_image = cv2.merge((b_channel, g_channel, r_channel, alpha_channel.astype(np.uint8)))
res_tensor = numpy2tensor(result_image/255.0)
return (res_tensor,)
NODE_CLASS_MAPPINGS = {
"LightColorCulling": LightColorCulling,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"LightColorCulling": "LightColorCulling",
}
|