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