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 d902c94 commit b8efe6e
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 131 deletions.
131 changes: 5 additions & 126 deletions BK_Img2Color.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,14 @@
import sys
import os
import torch
import webcolors
from PIL import Image, ImageDraw, ImageFont
from colornamer import get_color_from_rgb
from numpy import ndarray

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import matplotlib

from numpy import ndarray
import numpy as np

sys.path.append(os.path.dirname(os.path.dirname(__file__)))


class BK_Img2Color:

@classmethod
Expand Down Expand Up @@ -64,8 +60,7 @@ def INPUT_TYPES(cls):
DESCRIPTION = "从输入图像中提取主要颜色,可指定颜色数量,支持排除特定颜色,并可选择生成互补色"

def __init__(self):
self.webcolor_dict = {**webcolors.CSS3_HEX_TO_NAMES, **webcolors.CSS2_HEX_TO_NAMES,
**webcolors.CSS21_HEX_TO_NAMES, **webcolors.HTML4_HEX_TO_NAMES}
pass

def main(self, input_image: torch.Tensor, num_colors: int = 5, accuracy: int = 80,
get_complementary_color: bool = False, exclude_colors: str = "", select_color: int = 1) -> Tuple[str, str]:
Expand Down Expand Up @@ -112,126 +107,10 @@ def interrogate_colors(self, image: torch.Tensor, num_colors: int) -> List[ndarr
colors = kmeans.fit(pixels).cluster_centers_ * 255
return colors

def generate_color_blocks(self, color_string: str) -> np.ndarray:
colors = color_string.split(', ')
fig, axs = plt.subplots(1, len(colors), figsize=(
len(colors)*2, 2), squeeze=False)
axs = axs.flatten() # 将 axs 转换为一维数组,便于迭代

for ax, color in zip(axs, colors):
ax.imshow(np.full((10, 10, 3), np.array(
matplotlib.colors.to_rgb(color))))
ax.axis('off')

plt.tight_layout()
# plt.savefig('d:\\color_blocks.png')

return plt

def generate_palette(self, img: torch.Tensor, n_colors=16, cell_size=128, padding=0, font_path=None, font_size=15, mode='chart'):

img = img.resize((img.width // 2, img.height // 2),
resample=Image.BILINEAR)
pixels = np.array(img)
pixels = pixels.reshape((-1, 3))
kmeans = KMeans(n_clusters=n_colors, random_state=0,
n_init='auto').fit(pixels)
cluster_centers = np.uint8(kmeans.cluster_centers_)

# Get the sorted indices based on luminance
luminance = np.sqrt(np.dot(cluster_centers, [0.299, 0.587, 0.114]))
sorted_indices = np.argsort(luminance)

# Rearrange the cluster centers and luminance based on sorted indices
cluster_centers = cluster_centers[sorted_indices]
luminance = luminance[sorted_indices]

# Group colors by their individual types
reds = []
greens = []
blues = []
others = []

for i in range(n_colors):
color = cluster_centers[i]
color_type = np.argmax(color) # Find the dominant color component

if color_type == 0:
reds.append((color, luminance[i]))
elif color_type == 1:
greens.append((color, luminance[i]))
elif color_type == 2:
blues.append((color, luminance[i]))
else:
others.append((color, luminance[i]))

# Sort each color group by luminance
reds.sort(key=lambda x: x[1])
greens.sort(key=lambda x: x[1])
blues.sort(key=lambda x: x[1])
others.sort(key=lambda x: x[1])

# Combine the sorted color groups
sorted_colors = reds + greens + blues + others

if mode == 'back_to_back':
# Calculate the size of the palette image based on the number of colors
palette_width = n_colors * cell_size
palette_height = cell_size
else:
# Calculate the number of rows and columns based on the number of colors
num_rows = int(np.sqrt(n_colors))
num_cols = int(np.ceil(n_colors / num_rows))

# Calculate the size of the palette image based on the number of rows and columns
palette_width = num_cols * cell_size
palette_height = num_rows * cell_size

palette_size = (palette_width, palette_height)

palette = Image.new('RGB', palette_size, color='white')
draw = ImageDraw.Draw(palette)
if font_path:
font = ImageFont.truetype(font_path, font_size)
else:
font = ImageFont.load_default()

hex_palette = []
for i, (color, _) in enumerate(sorted_colors):
if mode == 'back_to_back':
cell_x = i * cell_size
cell_y = 0
else:
row = i % num_rows
col = i // num_rows
cell_x = col * cell_size
cell_y = row * cell_size

cell_width = cell_size
cell_height = cell_size

color = tuple(color)

cell = Image.new('RGB', (cell_width, cell_height), color=color)
palette.paste(cell, (cell_x, cell_y))

if mode != 'back_to_back':
text_x = cell_x + (cell_width / 2)
text_y = cell_y + cell_height + padding

draw.text((text_x + 1, text_y + 1),
f"R: {color[0]} G: {color[1]} B: {color[2]}", font=font, fill='black', anchor='ms')
draw.text(
(text_x, text_y), f"R: {color[0]} G: {color[1]} B: {color[2]}", font=font, fill='white', anchor='ms')

hex_palette.append('#%02x%02x%02x' % color)

return palette, '\n'.join(hex_palette)


if __name__ == "__main__":
bk_img2color = BK_Img2Color()
input_path = r"E:\\ComfyUI\\input\\ice.png"
input_path = r"./GetImageColor.png"
input_image = Image.open(input_path)
input_tensor = torch.from_numpy(
np.array(input_image)).permute(2, 0, 1).float() / 255.0
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[project]
name = "comfyui_baikong_node"
description = "Nodes:BK Img To Color, BK Color Selector"
description = "Nodes for advanced color manipulation and image processing: BK Img To Color, BK Color Selector, BK Color Contrast, BK Color Limit, BK Color Luminance, BK Gradient Image, and BK Image Aspect Filter."
version = "1.1.5"
license = { file = "LICENSE" }
dependencies = ["colornamer==0.2.4", "scikit_learn==1.4.0", "webcolors==1.11"]
dependencies = ["scikit_learn>=1.4.0",]

[project.urls]
Repository = "https://github.com/JayLyu/ComfyUI_BaiKong_Node"
Expand Down
4 changes: 1 addition & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
colornamer==0.2.4
scikit_learn==1.4.0
webcolors==1.11
scikit_learn>=1.4.0
matplotlib

0 comments on commit b8efe6e

Please sign in to comment.