Repository navigation
Expand file tree
/
Copy pathRemoveBackgroundAndResizeNode.py
More file actions
411 lines (353 loc) · 14 KB
/
Copy pathRemoveBackgroundAndResizeNode.py
File metadata and controls
411 lines (353 loc) · 14 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""
RemoveBackgroundAndResizeNode
============================
Single-file ComfyUI node for background removal with integrated resize.
Based on ``TransparencyBackgroundRemover`` and ``ScalingMixin`` from the
ComfyUI-TransparencyBackgroundRemover package. Adapted for standalone use
with minimal dependencies — PIL only for background removal, no hard
OpenCV requirement.
Author: Gero Doll / Limbicnation
License: Apache-2.0
"""
from __future__ import annotations
import logging
from typing import Tuple
import numpy as np
import torch
from PIL import Image
try:
import structlog
log = structlog.get_logger(__name__)
except ImportError:
log = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# ScalingMixin — shared resize logic (see scaling.py)
# ---------------------------------------------------------------------------
try:
from .scaling import ScalingMixin # noqa: F401 — re-exported for convenience
except ImportError:
from scaling import ScalingMixin
# ---------------------------------------------------------------------------
# PIL-only background removal
# ---------------------------------------------------------------------------
def _kmeans_colors(
arr: np.ndarray, n_clusters: int, tol: float = 0.01, max_iter: int = 20,
max_samples: int = 50000,
) -> np.ndarray:
"""
Simple k-means on pixel array [H*W, channels].
Returns ``(n_clusters, channels)`` cluster centres.
Fallback when scikit-learn is unavailable.
Parameters
----------
arr : np.ndarray
Input image array (H, W, C).
n_clusters : int
Number of k-means clusters.
tol : float
Convergence tolerance for centre shift.
max_iter : int
Maximum k-means iterations.
max_samples : int
Cap on number of pixels fed to k-means to avoid OOM on large images.
Subsampled uniformly when pixel count exceeds this value.
"""
pixels = arr.reshape(-1, arr.shape[-1]).astype(np.float32)
# Subsample to avoid OOM on large images (e.g. 4K → 8.3M pixels)
if len(pixels) > max_samples:
rng = np.random.RandomState(42)
idx = rng.choice(len(pixels), size=max_samples, replace=False)
pixels = pixels[idx]
indices = np.random.RandomState(42).choice(
len(pixels), size=n_clusters, replace=False
)
centres = pixels[indices].copy()
for _ in range(max_iter):
dists = np.linalg.norm(pixels[:, None] - centres[None], axis=-1)
labels = dists.argmin(axis=1)
new_centres = np.stack([pixels[labels == i].mean(axis=0) for i in range(n_clusters)])
if np.abs(new_centres - centres).max() < tol:
break
centres = new_centres
return centres
def _dominant_bg(arr: np.ndarray, samples: int = 5000) -> np.ndarray:
"""Sample corners + border to estimate background colour."""
h, w = arr.shape[:2]
mask = np.zeros((h, w), dtype=bool)
bw = max(1, min(h, w) // 10)
# top / bottom strips and left / right strips (intersection gives the four corners)
mask[:bw, :] = True
mask[-bw:, :] = True
mask[:, :bw] = True
mask[:, -bw:] = True
bg_pixels = arr[mask]
if len(bg_pixels) > samples:
idx = np.random.RandomState(42).choice(len(bg_pixels), samples, replace=False)
bg_pixels = bg_pixels[idx]
return bg_pixels.mean(axis=0).astype(np.uint8)
def remove_background_pil(
image: Image.Image,
tolerance: int = 30,
color_clusters: int = 8,
foreground_bias: float = 0.7,
binary_threshold: int = 128,
dither_handling: bool = True,
) -> Image.Image:
"""
Remove background from a PIL Image using colour clustering.
Pipeline
--------
1. Flatten to ``[H*W, channels]`` and run k-means to find dominant colours.
2. Identify background as the colour most similar to image edges / corners.
3. Compute per-pixel distance to foreground centres; keep pixels that are
closer than ``tolerance`` (adjusted by ``foreground_bias``).
4. Apply simple edge refinement via binary thresholding.
5. Return ``RGBA`` PIL Image.
Parameters
----------
image : PIL.Image
Input image (RGB or RGBA; RGBA ``A`` is ignored).
tolerance : int
Colour distance threshold (0-255). Higher = more pixels accepted as foreground.
color_clusters : int
K-means centres used to identify distinct colours.
foreground_bias : float
Bias towards keeping pixels (0 = discard more, 1 = keep more).
binary_threshold : int
Threshold for alpha mask binarisation (0-255).
dither_handling : bool
When True, apply a 1-pixel border erosion to reduce dither artefacts.
Returns
-------
PIL.Image
RGBA image with transparent background.
"""
rgb = image.convert("RGB")
arr = np.array(rgb, dtype=np.float32) # [H, W, 3]
# 1. k-means colour clustering
if color_clusters < 2:
color_clusters = 2
centres = _kmeans_colors(arr, color_clusters)
# 2. background colour from image perimeter
bg_colour = _dominant_bg(arr)
# 3. distance of each pixel to background vs foreground centres
h, w = arr.shape[:2]
flat = arr.reshape(-1, 3)
bg_dist = np.linalg.norm(flat - bg_colour.astype(np.float32), axis=1)
fg_dist = np.linalg.norm(
flat[:, None] - centres.astype(np.float32), axis=-1
).min(axis=1)
# effective tolerance — foreground_bias shifts the acceptance boundary
effective_tol = tolerance * (1.5 - foreground_bias)
mask = (fg_dist + effective_tol) < bg_dist
alpha = mask.reshape(h, w).astype(np.uint8) * 255
# 4. edge refinement
if dither_handling:
from PIL import ImageFilter
alpha_pil = Image.fromarray(alpha, mode="L")
alpha_pil = alpha_pil.filter(ImageFilter.MinFilter(3))
alpha = np.array(alpha_pil)
# 5. binarise
alpha = (alpha > binary_threshold).astype(np.uint8) * 255
# 6. assemble RGBA
result = np.dstack([arr.astype(np.uint8), alpha])
return Image.fromarray(result, mode="RGBA")
# ---------------------------------------------------------------------------
# ComfyUI node
# ---------------------------------------------------------------------------
class RemoveBackgroundAndResizeNode(ScalingMixin):
"""
Combines background removal and resize in a single node.
``INPUT_TYPES`` exposes tolerance, edge sensitivity, colour-cluster, and
output-size controls so the node can be dropped into any workflow without
separate background-removal and resize chains.
Outputs
-------
IMAGE : RGBA tensor (N, H, W, 4), values 0-1
MASK : greyscale alpha tensor (N, H, W), values 0-1
"""
# ------------------------------------------------------------------
# ComfyUI contract
# ------------------------------------------------------------------
RETURN_TYPES = ("IMAGE", "MASK")
RETURN_NAMES = ("image", "mask")
FUNCTION = "process"
CATEGORY = "image/processing"
OUTPUT_NODE = True
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE", {"tooltip": "Input image tensor from upstream node"}),
"tolerance": (
"INT",
{
"default": 30,
"min": 0,
"max": 255,
"step": 1,
"display": "number",
"tooltip": (
"Colour distance threshold. Higher = more aggressive "
"foreground extraction (0-255)."
),
},
),
"foreground_bias": (
"FLOAT",
{
"default": 0.7,
"min": 0.0,
"max": 1.0,
"step": 0.01,
"display": "slider",
"tooltip": (
"Bias toward keeping pixels as foreground. "
"Higher = more pixels preserved."
),
},
),
"color_clusters": (
"INT",
{
"default": 8,
"min": 2,
"max": 20,
"step": 1,
"display": "number",
"tooltip": "Number of k-means centres for colour segmentation.",
},
),
"output_size": (
[
"ORIGINAL",
"512x512",
"768x768",
"1024x1024",
"1280x720",
"1920x1080",
],
{
"default": "ORIGINAL",
"tooltip": (
"Resize output to this size. "
"ORIGINAL keeps source dimensions."
),
},
),
"scaling_method": (
["NEAREST", "BILINEAR", "BICUBIC", "LANCZOS"],
{
"default": "LANCZOS",
"tooltip": (
"Interpolation method. "
"LANCZOS = best quality; "
"NEAREST = pixel-perfect for pixel art."
),
},
),
},
"optional": {
"dither_handling": (
"BOOLEAN",
{
"default": True,
"tooltip": "Apply edge erosion to suppress dither artefacts.",
},
),
"binary_threshold": (
"INT",
{
"default": 128,
"min": 0,
"max": 255,
"step": 1,
"display": "number",
"tooltip": "Alpha mask binarisation cutoff (0-255).",
},
),
},
}
# ------------------------------------------------------------------
# processing
# ------------------------------------------------------------------
@torch.no_grad()
def process(
self,
image: torch.Tensor,
tolerance: int,
foreground_bias: float,
color_clusters: int,
output_size: str,
scaling_method: str,
dither_handling: bool = True,
binary_threshold: int = 128,
) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
"""
``image`` — ComfyUI IMAGE tensor, shape (N, H, W, C), float32 0-1.
Returns (IMAGE tensor, MASK tensor).
"""
# ------------------------------------------------------------------
# validation
# ------------------------------------------------------------------
if image is None or image.numel() == 0:
raise ValueError("RemoveBackgroundAndResizeNode: received empty image tensor.")
if image.ndim != 4:
raise ValueError(
f"RemoveBackgroundAndResizeNode: expected 4-D IMAGE tensor "
f"(N,H,W,C), got {image.ndim}-D."
)
if image.shape[-1] not in (3, 4):
raise ValueError(
f"RemoveBackgroundAndResizeNode: IMAGE must be RGB or RGBA; "
f"got channels={image.shape[-1]}."
)
# ------------------------------------------------------------------
# per-batch processing
# ------------------------------------------------------------------
rgba_tensors: list[torch.Tensor] = []
mask_tensors: list[torch.Tensor] = []
for i in range(image.shape[0]):
img_np = (image[i].cpu().numpy() * 255).clip(0, 255).astype(np.uint8)
# handle RGB input
if img_np.shape[-1] == 3:
pil_in = Image.fromarray(img_np, mode="RGB")
else:
pil_in = Image.fromarray(img_np[:, :, :3], mode="RGB")
# ---- remove background ----
pil_rgba = remove_background_pil(
pil_in,
tolerance=tolerance,
foreground_bias=foreground_bias,
color_clusters=color_clusters,
binary_threshold=binary_threshold,
dither_handling=dither_handling,
)
# ---- resize ----
pil_rgba = self.resize_image(pil_rgba, output_size, scaling_method)
# ---- back to tensor ----
arr = np.array(pil_rgba, dtype=np.float32) / 255.0
rgba_tensors.append(torch.from_numpy(arr))
# extract alpha channel as mask
mask_np = (np.array(pil_rgba.split()[3], dtype=np.float32) / 255.0)
mask_tensors.append(torch.from_numpy(mask_np))
# ------------------------------------------------------------------
# stack and return in ComfyUI tensor format
# ------------------------------------------------------------------
stacked_image: torch.Tensor = torch.stack(rgba_tensors).to(dtype=torch.float32)
stacked_mask: torch.Tensor = torch.stack(mask_tensors).to(dtype=torch.float32)
# ComfyUI MASK convention: (N, H, W)
if stacked_mask.ndim == 4 and stacked_mask.shape[-1] == 1:
stacked_mask = stacked_mask.squeeze(-1)
log.debug(
"RemoveBackgroundAndResizeNode.done",
batch=image.shape[0],
output_size=output_size,
scaling_method=scaling_method,
)
return (stacked_image, stacked_mask)
# ComfyUI registration dict
NODE_CLASS_MAPPINGS = {"RemoveBackgroundAndResize": RemoveBackgroundAndResizeNode}
NODE_DISPLAY_NAME_MAPPINGS = {
"RemoveBackgroundAndResize": "Remove Background & Resize"
}