Skip to content

Commit

Permalink
优化代码结构
Browse files Browse the repository at this point in the history
  • Loading branch information
JayLyu committed Sep 16, 2024
1 parent 2865c26 commit d902c94
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 181 deletions.
19 changes: 5 additions & 14 deletions BK_ColorLimit.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def INPUT_TYPES(s):
}

CATEGORY = "⭐️Baikong"
RETURN_TYPES = ( "STRING", )
RETURN_TYPES = ("STRING", )
FUNCTION = "color_limit"
DESCRIPTION = "输入十六进制颜色,并根据设定的饱和度和亮度范围限制,生成新的颜色"

Expand All @@ -75,8 +75,8 @@ def color_limit(
brightness_end: float = 0.5,
):
# 将 hex_color 转换成 rgb 元组
hex_color = hex_color.lstrip('#')
rgb_color = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
rgb_color = tuple(int(hex_color.lstrip(
'#')[i:i+2], 16) for i in (0, 2, 4))

# 将 rgb 转换成 hsl
h, s, l = rgb_to_hsl(rgb_color)
Expand All @@ -86,10 +86,8 @@ def color_limit(
s = round(s, 6)
l = round(l, 6)

# s 的值必须在 saturation_start 和 saturation_end 之间
# s 和 l 的值必须在指定范围内
s_new = max(saturation_start, min(s, saturation_end))

# l 的值必须在 brightness_start 和 brightness_end 之间
l_new = max(brightness_start, min(l, brightness_end))

# 将 hsl 的值转换为 rgb
Expand All @@ -98,14 +96,7 @@ def color_limit(
# 构造新的 hex 表示
hex_new = '#{:02x}{:02x}{:02x}'.format(*rgb_new)

# 构造 RGB 的字符串表示
rgb_string = f"({rgb_new[0]}, {rgb_new[1]}, {rgb_new[2]})"

# 构造 HSL 的字符串表示
hsl_string = f"({h}, {s_new}, {l_new})"

out = hex_new
return {"ui": {"text": (out,)}, "result": (out,)}
return {"ui": {"text": (hex_new,)}, "result": (hex_new,)}


if __name__ == "__main__":
Expand Down
17 changes: 7 additions & 10 deletions BK_ColorLuminance.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,19 @@ def exec(
light_text_hex_color = light_text_hex_color or "#FFFFFF"
dark_text_hex_color = dark_text_hex_color or "#000000"

bg_r, bg_g, bg_b = int(bg_hex_color[1:3], 16), int(
bg_hex_color[3:5], 16), int(bg_hex_color[5:7], 16)
bg_r, bg_g, bg_b = self.hex_to_rgb(bg_hex_color)
bg_luminance = relative_luminance(bg_r, bg_g, bg_b)

print(
f"背景: {bg_hex_color}, 明度: {bg_luminance:.4f}, 阈值: {luminance_threshold}")
print(f"背景: {bg_hex_color}, 明度: {bg_luminance:.4f}, 阈值: {luminance_threshold}")

if bg_luminance > luminance_threshold:
text_color = dark_text_hex_color
print(f"选择暗色文本: {text_color}")
else:
text_color = light_text_hex_color
print(f"选择亮色文本: {text_color}")
text_color = dark_text_hex_color if bg_luminance > luminance_threshold else light_text_hex_color
print(f"选择{'暗' if bg_luminance > luminance_threshold else '亮'}色文本: {text_color}")

return {"ui": {"text": (bg_hex_color, text_color)}, "result": (bg_hex_color, text_color)}

@staticmethod
def hex_to_rgb(hex_color):
return tuple(int(hex_color[i:i+2], 16) for i in (1, 3, 5))

# 测试代码
if __name__ == "__main__":
Expand Down
25 changes: 16 additions & 9 deletions BK_ColorSelector.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,29 @@ def INPUT_TYPES(s):

def select_color(
self,
hex_colors,
hex_colors: str,
symbol: str = ",",
split_count: int = 1,
):
# 将 str 分割成 list
color_list = hex_colors.split(symbol)
) -> dict:
# 将 str 分割成 list,并去除每个颜色周围的空白
color_list = [color.strip() for color in hex_colors.split(symbol)]

# 确保值在有效范围内
split_count = max(0, min(split_count - 1, len(color_list) - 1))
split_count = max(1, min(split_count, len(color_list))) - 1

# 提取指定颜色
selected_color = color_list[split_count]
# 去掉多余的空格
selected_color = selected_color.replace(" ", "")

# 验证颜色格式
if not self.is_valid_hex_color(selected_color):
raise ValueError(f"无效的十六进制颜色: {selected_color}")

out = selected_color
return {"ui": {"text": (out,)}, "result": (out,)}
return {"ui": {"text": (selected_color,)}, "result": (selected_color,)}

@staticmethod
def is_valid_hex_color(color: str) -> bool:
import re
return bool(re.match(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color))

if __name__ == "__main__":
selector_node = BK_ColorSelector()
Expand Down
48 changes: 24 additions & 24 deletions BK_GradientImage.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ def INPUT_TYPES(s):
OUTPUT_NODE = False
DESCRIPTION = "生成指定尺寸的渐变图像,支持水平或垂直方向,可调整起始位置、结束位置和颜色"

@staticmethod
def hex_to_rgb(hex_color):
return tuple(int(hex_color[i:i+2], 16) for i in (1, 3, 5))

def main(
self,
hex_color: str = "#FFFFFF",
Expand All @@ -57,33 +61,29 @@ def main(
image = Image.new("RGBA", (width, height))
draw = ImageDraw.Draw(image)

r, g, b = int(hex_color[1:3], 16), int(
hex_color[3:5], 16), int(hex_color[5:7], 16)

if direction == 'horizontal':
start_x = int(width * start_position)
midpoint_x = int(width * end_position)
for x in range(start_x, midpoint_x):
alpha = int(255 * (x - start_x) / (midpoint_x - start_x))
draw.line((x, 0, x, height), fill=(r, g, b, alpha))
# Fill the rest from midpoint_x to the end with solid color
draw.rectangle([midpoint_x, 0, width, height], fill=(r, g, b, 255))
else: # vertical
start_y = int(height * start_position)
midpoint_y = int(height * end_position)
for y in range(start_y, midpoint_y):
alpha = int(255 * (y - start_y) / (midpoint_y - start_y))
draw.line((0, y, width, y), fill=(r, g, b, alpha))
# Fill the rest from midpoint_y to the end with solid color
draw.rectangle([0, midpoint_y, width, height], fill=(r, g, b, 255))

# 旋转图像
r, g, b = self.hex_to_rgb(hex_color)

is_horizontal = direction == 'horizontal'
size = width if is_horizontal else height
start = int(size * start_position)
end = int(size * end_position)

for i in range(start, end):
alpha = int(255 * (i - start) / (end - start))
color = (r, g, b, alpha)
if is_horizontal:
draw.line((i, 0, i, height), fill=color)
else:
draw.line((0, i, width, i), fill=color)

# 填充剩余部分
fill_area = [end, 0, size, height] if is_horizontal else [0, end, width, size]
draw.rectangle(fill_area, fill=(r, g, b, 255))

if reverse:
image = image.rotate(180)

image_out = pil2tensor(image)

return (image_out,)
return (pil2tensor(image),)


if __name__ == "__main__":
Expand Down
62 changes: 62 additions & 0 deletions BK_ImageAspectFilter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import torch
from PIL import Image
import numpy as np
import base64

# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))

# Convert PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)

class BK_ImageAspectFilter:

@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE",),
"min_aspect_ratio": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.01}),
"max_aspect_ratio": ("FLOAT", {"default": 1.2, "min": 0.1, "max": 10.0, "step": 0.01}),
"default_image": ("IMAGE",),
}
}

RETURN_TYPES = ("IMAGE",)
FUNCTION = "filter"
CATEGORY = "⭐️Baikong"

def filter(self, images, min_aspect_ratio: float, max_aspect_ratio: float, default_image):
valid_images = []
ui_text = []

# 确保 images 是 4D 张量 (batch, height, width, channels)
if len(images.shape) != 4:
raise ValueError(f"输入图像的形状不正确。预期为 (batch, height, width, channels),实际为 {images.shape}")

batch_size, height, width, channels = images.shape

for i in range(batch_size):
aspect_ratio = width / height

ui_text.append(f"image {i} - 宽高比: {aspect_ratio:.4f} - 尺寸: ({width}, {height})")

# 检查宽高比是否在给定范围内
if min_aspect_ratio <= aspect_ratio <= max_aspect_ratio:
valid_images.append(images[i].unsqueeze(0))

if not valid_images:
ui_text.append("没有图像符合给定的宽高比标准。使用默认图像。")
valid_images = [default_image]

# 确保返回的是正确格式的张量
if len(valid_images) == 1:
valid_images = valid_images[0]
else:
valid_images = torch.cat(valid_images, dim=0)

ui_text = "\n".join(ui_text)

return {"ui": {"text": f"text:{valid_images, ui_text}"}, "result": (valid_images, ui_text)}
67 changes: 0 additions & 67 deletions BK_ImageFilterByAspectRatio.py

This file was deleted.

Loading

0 comments on commit d902c94

Please sign in to comment.