nodes_mask.py 12 KB
Newer Older
1
import numpy as np
2
import scipy.ndimage
3
import torch
4
import comfy.utils
5
6
7

from nodes import MAX_RESOLUTION

8
def composite(destination, source, x, y, mask = None, multiplier = 8, resize_source = False):
9
    source = source.to(destination.device)
10
11
12
    if resize_source:
        source = torch.nn.functional.interpolate(source, size=(destination.shape[2], destination.shape[3]), mode="bilinear")

13
14
    source = comfy.utils.repeat_to_batch_size(source, destination.shape[0])

15
16
17
18
19
20
21
22
23
    x = max(-source.shape[3] * multiplier, min(x, destination.shape[3] * multiplier))
    y = max(-source.shape[2] * multiplier, min(y, destination.shape[2] * multiplier))

    left, top = (x // multiplier, y // multiplier)
    right, bottom = (left + source.shape[3], top + source.shape[2],)

    if mask is None:
        mask = torch.ones_like(source)
    else:
24
        mask = mask.to(destination.device, copy=True)
25
26
        mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(source.shape[2], source.shape[3]), mode="bilinear")
        mask = comfy.utils.repeat_to_batch_size(mask, source.shape[0])
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

    # calculate the bounds of the source that will be overlapping the destination
    # this prevents the source trying to overwrite latent pixels that are out of bounds
    # of the destination
    visible_width, visible_height = (destination.shape[3] - left + min(0, x), destination.shape[2] - top + min(0, y),)

    mask = mask[:, :, :visible_height, :visible_width]
    inverse_mask = torch.ones_like(mask) - mask

    source_portion = mask * source[:, :, :visible_height, :visible_width]
    destination_portion = inverse_mask  * destination[:, :, top:bottom, left:right]

    destination[:, :, top:bottom, left:right] = source_portion + destination_portion
    return destination

42
43
44
45
46
47
48
class LatentCompositeMasked:
    @classmethod
    def INPUT_TYPES(s):
        return {
            "required": {
                "destination": ("LATENT",),
                "source": ("LATENT",),
49
50
                "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
                "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
51
                "resize_source": ("BOOLEAN", {"default": False}),
52
53
54
55
56
57
58
59
60
61
            },
            "optional": {
                "mask": ("MASK",),
            }
        }
    RETURN_TYPES = ("LATENT",)
    FUNCTION = "composite"

    CATEGORY = "latent"

62
    def composite(self, destination, source, x, y, resize_source, mask = None):
63
64
65
        output = destination.copy()
        destination = destination["samples"].clone()
        source = source["samples"]
66
        output["samples"] = composite(destination, source, x, y, mask, 8, resize_source)
67
        return (output,)
68

69
70
71
72
73
74
75
76
77
class ImageCompositeMasked:
    @classmethod
    def INPUT_TYPES(s):
        return {
            "required": {
                "destination": ("IMAGE",),
                "source": ("IMAGE",),
                "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
78
                "resize_source": ("BOOLEAN", {"default": False}),
79
80
81
82
83
84
85
            },
            "optional": {
                "mask": ("MASK",),
            }
        }
    RETURN_TYPES = ("IMAGE",)
    FUNCTION = "composite"
86

87
    CATEGORY = "image"
88

89
    def composite(self, destination, source, x, y, resize_source, mask = None):
90
        destination = destination.clone().movedim(-1, 1)
91
        output = composite(destination, source.movedim(-1, 1), x, y, mask, 1, resize_source).movedim(1, -1)
92
93
94
95
        return (output,)

class MaskToImage:
    @classmethod
96
    def INPUT_TYPES(s):
97
        return {
98
99
100
                "required": {
                    "mask": ("MASK",),
                }
101
102
103
104
105
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("IMAGE",)
106
107
108
    FUNCTION = "mask_to_image"

    def mask_to_image(self, mask):
109
        result = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
110
111
112
113
114
115
116
117
        return (result,)

class ImageToMask:
    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                    "image": ("IMAGE",),
118
                    "channel": (["red", "green", "blue", "alpha"],),
119
120
                }
        }
121

122
    CATEGORY = "mask"
123

124
125
    RETURN_TYPES = ("MASK",)
    FUNCTION = "image_to_mask"
126

127
    def image_to_mask(self, image, channel):
128
        channels = ["red", "green", "blue", "alpha"]
129
        mask = image[:, :, :, channels.index(channel)]
130
        return (mask,)
131

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class ImageColorToMask:
    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                    "image": ("IMAGE",),
                    "color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
                }
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)
    FUNCTION = "image_to_mask"

    def image_to_mask(self, image, color):
148
149
        temp = (torch.clamp(image, 0, 1.0) * 255.0).round().to(torch.int)
        temp = torch.bitwise_left_shift(temp[:,:,:,0], 16) + torch.bitwise_left_shift(temp[:,:,:,1], 8) + temp[:,:,:,2]
150
151
152
        mask = torch.where(temp == color, 255, 0).float()
        return (mask,)

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
class SolidMask:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "value": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
                "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
                "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
            }
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)

    FUNCTION = "solid"

    def solid(self, value, width, height):
171
        out = torch.full((1, height, width), value, dtype=torch.float32, device="cpu")
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
        return (out,)

class InvertMask:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "mask": ("MASK",),
            }
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)

    FUNCTION = "invert"

    def invert(self, mask):
        out = 1.0 - mask
        return (out,)

class CropMask:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "mask": ("MASK",),
                "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
                "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
            }
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)

    FUNCTION = "crop"

    def crop(self, mask, x, y, width, height):
213
214
        mask = mask.reshape((-1, mask.shape[-2], mask.shape[-1]))
        out = mask[:, y:y + height, x:x + width]
215
216
217
218
219
220
221
222
223
224
225
        return (out,)

class MaskComposite:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "destination": ("MASK",),
                "source": ("MASK",),
                "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
space-nuko's avatar
space-nuko committed
226
                "operation": (["multiply", "add", "subtract", "and", "or", "xor"],),
227
228
229
230
231
232
233
234
235
236
            }
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)

    FUNCTION = "combine"

    def combine(self, destination, source, x, y, operation):
237
238
        output = destination.reshape((-1, destination.shape[-2], destination.shape[-1])).clone()
        source = source.reshape((-1, source.shape[-2], source.shape[-1]))
239
240

        left, top = (x, y,)
241
        right, bottom = (min(left + source.shape[-1], destination.shape[-1]), min(top + source.shape[-2], destination.shape[-2]))
242
243
        visible_width, visible_height = (right - left, bottom - top,)

Jairo Correa's avatar
Jairo Correa committed
244
245
        source_portion = source[:, :visible_height, :visible_width]
        destination_portion = destination[:, top:bottom, left:right]
246

comfyanonymous's avatar
comfyanonymous committed
247
        if operation == "multiply":
248
            output[:, top:bottom, left:right] = destination_portion * source_portion
comfyanonymous's avatar
comfyanonymous committed
249
        elif operation == "add":
250
            output[:, top:bottom, left:right] = destination_portion + source_portion
comfyanonymous's avatar
comfyanonymous committed
251
        elif operation == "subtract":
252
            output[:, top:bottom, left:right] = destination_portion - source_portion
space-nuko's avatar
space-nuko committed
253
        elif operation == "and":
254
            output[:, top:bottom, left:right] = torch.bitwise_and(destination_portion.round().bool(), source_portion.round().bool()).float()
space-nuko's avatar
space-nuko committed
255
        elif operation == "or":
256
            output[:, top:bottom, left:right] = torch.bitwise_or(destination_portion.round().bool(), source_portion.round().bool()).float()
space-nuko's avatar
space-nuko committed
257
        elif operation == "xor":
258
            output[:, top:bottom, left:right] = torch.bitwise_xor(destination_portion.round().bool(), source_portion.round().bool()).float()
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

        output = torch.clamp(output, 0.0, 1.0)

        return (output,)

class FeatherMask:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "mask": ("MASK",),
                "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
                "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
            }
        }

    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)

    FUNCTION = "feather"

    def feather(self, mask, left, top, right, bottom):
284
        output = mask.reshape((-1, mask.shape[-2], mask.shape[-1])).clone()
285

Jairo Correa's avatar
Jairo Correa committed
286
287
288
289
        left = min(left, output.shape[-1])
        right = min(right, output.shape[-1])
        top = min(top, output.shape[-2])
        bottom = min(bottom, output.shape[-2])
290
291
292

        for x in range(left):
            feather_rate = (x + 1.0) / left
293
            output[:, :, x] *= feather_rate
294
295
296

        for x in range(right):
            feather_rate = (x + 1) / right
297
            output[:, :, -x] *= feather_rate
298
299
300

        for y in range(top):
            feather_rate = (y + 1) / top
301
            output[:, y, :] *= feather_rate
302
303
304

        for y in range(bottom):
            feather_rate = (y + 1) / bottom
305
            output[:, -y, :] *= feather_rate
306
307

        return (output,)
308
309
310
311
312
313
314
    
class GrowMask:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "mask": ("MASK",),
315
                "expand": ("INT", {"default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1}),
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                "tapered_corners": ("BOOLEAN", {"default": True}),
            },
        }
    
    CATEGORY = "mask"

    RETURN_TYPES = ("MASK",)

    FUNCTION = "expand_mask"

    def expand_mask(self, mask, expand, tapered_corners):
        c = 0 if tapered_corners else 1
        kernel = np.array([[c, 1, c],
                           [1, 1, 1],
                           [c, 1, c]])
331
332
333
334
        mask = mask.reshape((-1, mask.shape[-2], mask.shape[-1]))
        out = []
        for m in mask:
            output = m.numpy()
335
336
337
338
339
            for _ in range(abs(expand)):
                if expand < 0:
                    output = scipy.ndimage.grey_erosion(output, footprint=kernel)
                else:
                    output = scipy.ndimage.grey_dilation(output, footprint=kernel)
340
341
            output = torch.from_numpy(output)
            out.append(output)
342
        return (torch.stack(out, dim=0),)
343
344
345
346
347



NODE_CLASS_MAPPINGS = {
    "LatentCompositeMasked": LatentCompositeMasked,
348
    "ImageCompositeMasked": ImageCompositeMasked,
349
    "MaskToImage": MaskToImage,
350
    "ImageToMask": ImageToMask,
351
    "ImageColorToMask": ImageColorToMask,
352
353
354
355
356
    "SolidMask": SolidMask,
    "InvertMask": InvertMask,
    "CropMask": CropMask,
    "MaskComposite": MaskComposite,
    "FeatherMask": FeatherMask,
357
    "GrowMask": GrowMask,
358
359
}

360
361
362
363
NODE_DISPLAY_NAME_MAPPINGS = {
    "ImageToMask": "Convert Image to Mask",
    "MaskToImage": "Convert Mask to Image",
}