Extract Color Palette
어떤 입력 이미지에서든 일관된 색상 팔레트를 추출하고, 이를 깔끔한 풀 해상도 색상 바로 렌더링합니다. 추출할 색상 수와, 각 색상의 너비를 이미지에서의 시각적 지배력에 비례하게 할지 또는 모든 색상을 동일 비율로 표시할지 선택할 수 있습니다.
정보
이 ComfyUI 워크플로는 어떤 입력 이미지에서든 일관된 색상 팔레트를 추출해, 깔끔한 전체 해상도의 색상 바 형태로 렌더링합니다. 포함할 색상 수와 각 스와치의 너비를 동일하게 할지, 소스에서의 시각적 지배도에 비례하게 할지 제어할 수 있습니다. 결과는 무드보드, 브랜딩 가이드, UI 토큰, 색상 스터디 참고 자료에 적합한 공유용 팔레트 이미지입니다.
기술적으로 파이프라인은 단순하고 빠릅니다. LoadImage로 소스 이미지를 그래프에 불러온 뒤, GLSLShader가 픽셀 색상을 분석하고 유사한 색상을 N개의 버킷으로 묶고 상대적인 비중을 추정해 최종 가로 팔레트를 그립니다. PrimitiveInt는 목표 색상 수를 설정하고, ComfySwitchNode는 동일 너비 스와치와 지배도 가중 스와치 간 전환을 담당합니다. ResolutionSelector로 출력 크기를 정확히 설정하고, SaveImageAdvanced로 파일 이름 및 저장 위치를 제어합니다. 모든 과정이 ComfyUI 안에서 실행되므로, 몇 가지 노드 값을 조정한 뒤 다시 실행 대기열에 넣어 빠르게 반복할 수 있습니다.
제공할 항목
- 워크플로 읽는 중
ComfyUI에서 실행됩니다. 이 워크플로는 이 페이지에서 실행할 수 없습니다. 모든 항목이 로드된 Comfy Cloud에서 열거나, 자체 ComfyUI에서 사용하려면 다운로드하세요.
Cloud에서 사용해 보기예시 사용해 보기
워크플로 내부
노드 그래프의 읽기 전용 미리보기입니다. 노드를 편집하려면 Comfy Cloud에서 열거나 다운로드하세요.
Loading the graph
Open full-size workflow preview- 작성자
- Rob
사용자 지정 노드 필요
- 워크플로 읽는 중
코드에서 이 워크플로 사용하기
가능한 경우 워크플로 그래프와 입력을 기반으로 생성되며, 그렇지 않은 경우 저장된 예시가 표시됩니다. 비용이 발생할 수 있으므로 코드를 실행하기 전에 자격 증명과 엔드포인트를 검토하세요.
What you need
- Runs on
- Comfy Cloud
- 키
- COMFY_API_KEY
- 내 파일
- 코드가 해당 URL에서 업로드
유료 Cloud 요금제와 크레딧이 필요합니다.
# Python 3.10+: pip install comfy-sdk==0.4.0
import os
from comfy_sdk import Comfy
api_key = os.environ.get("COMFY_API_KEY", "").strip()
if not api_key: raise RuntimeError("Set COMFY_API_KEY")
os.environ.setdefault("COMFY_BASE_URL", "https://cloud.comfy.org")
client = Comfy(api_key=api_key)
workflow = client.workflows.from_json({
"148": {
"class_type": "LoadImage",
"inputs": {
"image": "UPLOADED_image_FILENAME"
},
"_meta": {
"title": "Load Image"
}
},
"149": {
"class_type": "GLSLShader",
"inputs": {
"fragment_shader": "#version 300 es\n// kmeans_palette.glsl — GPU k-means dominant colors -> vertical stripes.\n//\n// INPUTS\n// u_image0 — source image (required)\n// u_int0 — stripe count K (try this first)\n// u_float0 — stripe count K (use this if u_int0 doesn't update; this node\n// forwards floats more reliably than ints)\n// If neither input forwards a value, K falls back to DEFAULT_K below.\n//\n// OUTPUT SIZE: set on the node via size_mode -> custom (width / height),\n// not in the shader. Keep it >= ~64x64.\n\n#pragma passes 10\n\nprecision highp float;\n\nconst int DEFAULT_K = 8; // used only if no count input forwards\nconst int MAX_K = 16;\nconst int NUM_PASSES = 10; // keep equal to `#pragma passes` above\nconst int GRID = 48; // cached source samples per axis\n\nuniform sampler2D u_image0; // pass 0: SOURCE; pass 1+: ping-pong buffer\nuniform vec2 u_resolution;\nuniform int u_int0; // K (preferred)\nuniform float u_float0; // K (fallback path)\nuniform int u_pass;\n\nin vec2 v_texCoord;\nlayout(location = 0) out vec4 fragColor0;\n\nint resolveK() {\n int k = 0;\n if (u_int0 > 0) k = u_int0; // try the int input\n else if (u_float0 > 0.5) k = int(u_float0 + 0.5); // else the float input\n else k = DEFAULT_K; // else the constant\n return clamp(k, 2, MAX_K);\n}\n\nvec3 readCentroid(int i) { return texelFetch(u_image0, ivec2(i, 0), 0).rgb; }\nvec3 readCache(int sx, int sy) { return texelFetch(u_image0, ivec2(sx, sy + 1), 0).rgb; }\n\nint nearestCentroid(vec3 px, int K) {\n float best = 1e9;\n int bi = 0;\n for (int j = 0; j < MAX_K; j++) {\n if (j >= K) break;\n vec3 d = px - readCentroid(j);\n float dist = dot(d, d);\n if (dist < best) { best = dist; bi = j; }\n }\n return bi;\n}\n\nvoid main() {\n int K = resolveK();\n ivec2 frag = ivec2(gl_FragCoord.xy);\n\n // PASS 0: cache a GRID x GRID downsample of the source (rows 1..GRID) and\n // seed K centroids (row 0). On this pass u_image0 IS the source.\n if (u_pass == 0) {\n if (frag.y == 0 && frag.x < K) {\n float u = (float(frag.x) + 0.5) / float(K);\n float v = fract(u * 2.6180339887);\n fragColor0 = vec4(texture(u_image0, vec2(u, v)).rgb, 1.0);\n } else if (frag.y >= 1 && frag.y <= GRID && frag.x < GRID) {\n vec2 uv = (vec2(float(frag.x), float(frag.y - 1)) + 0.5) / float(GRID);\n fragColor0 = vec4(texture(u_image0, uv).rgb, 1.0);\n } else {\n fragColor0 = vec4(0.0, 0.0, 0.0, 1.0);\n }\n return;\n }\n\n // PASSES 1..N-2: one k-means iteration\n if (u_pass < NUM_PASSES - 1) {\n if (frag.y == 0 && frag.x < K) {\n int c = frag.x;\n vec3 sum = vec3(0.0);\n float cnt = 0.0;\n for (int sy = 0; sy < GRID; sy++) {\n for (int sx = 0; sx < GRID; sx++) {\n vec3 px = readCache(sx, sy);\n if (nearestCentroid(px, K) == c) { sum += px; cnt += 1.0; }\n }\n }\n fragColor0 = vec4(cnt > 0.0 ? sum / cnt : readCentroid(c), 1.0);\n } else {\n fragColor0 = texelFetch(u_image0, frag, 0);\n }\n return;\n }\n\n // FINAL PASS: K vertical stripes\n int band = clamp(int(v_texCoord.x * float(K)), 0, K - 1);\n fragColor0 = vec4(readCentroid(band), 1.0);\n}",
"images.image0": [
"148",
0
],
"ints.u_int0": [
"150",
0
],
"size_mode": "custom",
"size_mode.height": [
"153",
1
],
"size_mode.width": [
"153",
0
]
},
"_meta": {
"title": "GLSL Shader"
}
},
"150": {
"class_type": "PrimitiveInt",
"inputs": {
"value": 12
},
"_meta": {
"title": "Palette Size"
}
},
"151": {
"class_type": "GLSLShader",
"inputs": {
"fragment_shader": "#version 300 es\n// kmeans_palette_weighted.glsl — GPU k-means dominant colors as vertical stripes,\n// with each stripe's WIDTH proportional to that color's share of the image.\n// Widths are snapped to 2.5% increments (largest-remainder), so a colour that's\n// a tiny fraction rounds to 0% (disappears) or 2.5% min — no negligible slivers.\n//\n// INPUTS\n// u_image0 — source image (required)\n// u_int0 — max number of colors K (drive with the stock \"Int\" node)\n// u_float0 — same, fallback if u_int0 doesn't forward\n// If neither forwards, K = DEFAULT_K below.\n//\n// OUTPUT SIZE: set on the node via size_mode -> custom. Keep >= ~64x64.\n//\n// NOTE: stripes are NOT equal width here, so ShaderPaletteToHex (which samples\n// equal bands) won't line up — use the equal-width kmeans_palette.glsl for that.\n\n#pragma passes 10\n\nprecision highp float;\n\nconst int DEFAULT_K = 8;\nconst int MAX_K = 16;\nconst int NUM_PASSES = 10; // keep equal to `#pragma passes`\nconst int GRID = 48; // cached source samples per axis\nconst int STEPS = 40; // 100% / 2.5% -> stripe widths are multiples of 2.5%\nconst float TOTAL = float(GRID * GRID);\n\nuniform sampler2D u_image0; // pass 0: SOURCE; pass 1+: ping-pong buffer\nuniform vec2 u_resolution;\nuniform int u_int0;\nuniform float u_float0;\nuniform int u_pass;\n\nin vec2 v_texCoord;\nlayout(location = 0) out vec4 fragColor0;\n\nint resolveK() {\n int k = u_int0 > 0 ? u_int0 : (u_float0 > 0.5 ? int(u_float0 + 0.5) : DEFAULT_K);\n return clamp(k, 2, MAX_K);\n}\n\n// row 0: centroids — rgb = colour, a = cluster's share of samples (0..1)\n// rows 1..GRID: cached source downsample\nvec3 readColor(int i) { return texelFetch(u_image0, ivec2(i, 0), 0).rgb; }\nfloat readShare(int i) { return texelFetch(u_image0, ivec2(i, 0), 0).a; }\nvec3 readCache(int sx, int sy){ return texelFetch(u_image0, ivec2(sx, sy + 1), 0).rgb; }\n\nint nearestCentroid(vec3 px, int K) {\n float best = 1e9;\n int bi = 0;\n for (int j = 0; j < MAX_K; j++) {\n if (j >= K) break;\n vec3 d = px - readColor(j);\n float dist = dot(d, d);\n if (dist < best) { best = dist; bi = j; }\n }\n return bi;\n}\n\nvoid main() {\n int K = resolveK();\n ivec2 frag = ivec2(gl_FragCoord.xy);\n\n // PASS 0: cache source (rows 1..GRID) + seed centroids (row 0)\n if (u_pass == 0) {\n if (frag.y == 0 && frag.x < K) {\n float u = (float(frag.x) + 0.5) / float(K);\n float v = fract(u * 2.6180339887);\n fragColor0 = vec4(texture(u_image0, vec2(u, v)).rgb, 0.0);\n } else if (frag.y >= 1 && frag.y <= GRID && frag.x < GRID) {\n vec2 uv = (vec2(float(frag.x), float(frag.y - 1)) + 0.5) / float(GRID);\n fragColor0 = vec4(texture(u_image0, uv).rgb, 1.0);\n } else {\n fragColor0 = vec4(0.0);\n }\n return;\n }\n\n // PASSES 1..N-2: k-means iteration; store cluster share in alpha\n if (u_pass < NUM_PASSES - 1) {\n if (frag.y == 0 && frag.x < K) {\n int c = frag.x;\n vec3 sum = vec3(0.0);\n float cnt = 0.0;\n for (int sy = 0; sy < GRID; sy++) {\n for (int sx = 0; sx < GRID; sx++) {\n vec3 px = readCache(sx, sy);\n if (nearestCentroid(px, K) == c) { sum += px; cnt += 1.0; }\n }\n }\n vec3 col = cnt > 0.0 ? sum / cnt : readColor(c);\n fragColor0 = vec4(col, cnt / TOTAL); // alpha = share of samples\n } else {\n fragColor0 = texelFetch(u_image0, frag, 0);\n }\n return;\n }\n\n // FINAL PASS: weighted vertical stripes, widths snapped to 2.5% slots.\n // Largest-remainder allocation of STEPS slots so they sum to exactly 100%.\n int floorSlots[MAX_K];\n float rem[MAX_K];\n int used = 0;\n for (int j = 0; j < MAX_K; j++) {\n float share = (j < K) ? readShare(j) : 0.0;\n if (share > 0.0) {\n float rs = share * float(STEPS);\n int fs = int(floor(rs));\n floorSlots[j] = fs;\n rem[j] = rs - float(fs);\n used += fs;\n } else {\n floorSlots[j] = 0;\n rem[j] = -1.0; // empty/unused cluster never gets a slot\n }\n }\n int remaining = STEPS - used; // leftover slots (always fills to STEPS)\n\n // Each leftover slot goes to a largest-remainder cluster (rank-based, stable).\n int slots[MAX_K];\n for (int j = 0; j < MAX_K; j++) {\n int rank = 0;\n for (int m = 0; m < MAX_K; m++) {\n if (rem[m] > rem[j] || (rem[m] == rem[j] && m < j)) rank++;\n }\n slots[j] = floorSlots[j] + (rank < remaining ? 1 : 0);\n }\n\n // Render order: largest weight on the left -> smallest on the right.\n // Rank each cluster by slot count (desc, tie-break by index) to get a stable\n // left->right order, then place each cluster at its rank position.\n int order_[MAX_K];\n for (int j = 0; j < MAX_K; j++) {\n int rnk = 0;\n for (int m = 0; m < MAX_K; m++) {\n if (slots[m] > slots[j] || (slots[m] == slots[j] && m < j)) rnk++;\n }\n order_[rnk] = j;\n }\n\n // Which stripe does this pixel's x fall into, walking left->right by weight?\n float xslot = v_texCoord.x * float(STEPS);\n int cum = 0;\n int chosen = order_[0]; // widest, leftmost (safety default)\n for (int r = 0; r < MAX_K; r++) {\n cum += slots[order_[r]];\n if (xslot < float(cum)) { chosen = order_[r]; break; }\n }\n fragColor0 = vec4(readColor(chosen), 1.0);\n}\n",
"images.image0": [
"148",
0
],
"ints.u_int0": [
"150",
0
],
"size_mode": "custom",
"size_mode.height": [
"153",
1
],
"size_mode.width": [
"153",
0
]
},
"_meta": {
"title": "GLSL Shader"
}
},
"152": {
"class_type": "ComfySwitchNode",
"inputs": {
"on_false": [
"149",
0
],
"on_true": [
"151",
0
],
"switch": True
},
"_meta": {
"title": "If/Else Switch"
}
},
"153": {
"class_type": "ResolutionSelector",
"inputs": {
"aspect_ratio": "16:9 (Widescreen)",
"megapixels": 1,
"multiple": 8
},
"_meta": {
"title": "Resolution Selector"
}
},
"154": {
"class_type": "SaveImageAdvanced",
"inputs": {
"filename_prefix": "extracted_color_palette",
"format": "png",
"format.bit_depth": "8-bit",
"format.input_color_space": "sRGB",
"images": [
"152",
0
]
},
"_meta": {
"title": "Save Image (Advanced)"
}
}
})
# Replace each example.com URL with a public URL of your file.
workflow.set_input("148", "image", client.assets.from_url("https://example.com/replace-with-a-url/image"))
# run() also passes api_key to the partner nodes in this workflow.
job = client.run(workflow, api_key=api_key)질문과 답변
GLSLShader는 유사한 픽셀 색상을 지정된 버킷 수로 그룹화하고, 각 버킷이 이미지에서 차지하는 비율을 추정합니다. 그런 다음 선택한 모드(동일 또는 우세 비중)에 따라 상위 버킷의 스와치를 정렬하고 크기를 조정해 렌더링합니다.
각 색상이 동일한 시각적 비중을 갖는 균형 잡힌 팔레트가 필요하면 동일을 사용하세요. 이미지의 실제 색상 비율을 반영하려면 가중을 사용하세요. 분석, 그레이딩 레퍼런스, 데이터셋 QA에 유용합니다.
브랜딩 및 UI에는 보통 5~8색이 깔끔하고 활용하기 좋습니다. 복잡한 장면 또는 분석에는 10~16색이 더 많은 뉘앙스를 담을 수 있습니다. 너무 많으면 거의 같은 색이 중복될 수 있으니, 그런 경우 개수를 줄이거나 이미지에서 가장 관련 있는 영역만 크롭하세요.
압축이 심하거나 노이즈가 많거나 패턴이 강한 이미지는 작은 색상 조각을 만들어낼 수 있습니다. 더 좋은 품질의 소스를 사용하거나, 복잡한 영역을 크롭하거나, 색상 개수를 줄여 보세요. 가중 모드로 전환하면 중요하지 않은 작은 색상의 영향을 줄이는 데도 도움이 됩니다.
예. ResolutionSelector에서 정확한 크기를 설정해 팔레트 해상도를 제어하고, SaveImageAdvanced에서 출력 디렉토리 및 파일 이름 패턴을 구성하세요.