Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(nodes): read the real alpha channel in Mask from Alpha (#10173)

Mohammad Hijjawi44e846e791a8
diff --git a/invokeai/app/invocations/image.py b/invokeai/app/invocations/image.py
index ee73424df7..bb5726363f 100644
--- a/invokeai/app/invocations/image.py
+++ b/invokeai/app/invocations/image.py
@@ -230,7 +230,7 @@ class ImagePasteInvocation(BaseInvocation, WithMetadata, WithBoard):
title="Mask from Alpha",
tags=["image", "mask"],
category="mask",
- version="1.2.2",
+ version="1.3.0",
)
class MaskFromAlphaInvocation(BaseInvocation, WithMetadata, WithBoard):
"""Extracts the alpha channel of an image as a mask."""
@@ -241,7 +241,17 @@ class MaskFromAlphaInvocation(BaseInvocation, WithMetadata, WithBoard):
def invoke(self, context: InvocationContext) -> ImageOutput:
image = context.images.get_pil(self.image.image_name)
- image_mask = image.split()[-1]
+ if image.mode == "1":
+ # A one-bit image is already a black and white mask. Use it as an L image so that it inverts correctly.
+ image_mask = image.convert("L")
+ elif image.mode != "P" and len(image.getbands()) == 1:
+ # A grayscale image (L, I, I;16 or F) is already a mask, so use it as is.
+ image_mask = image
+ else:
+ # Converting gives an image without an alpha channel a fully opaque one. Its last band is a color or
+ # palette channel, not alpha.
+ image_mask = image.convert("RGBA").getchannel("A")
+
if self.invert:
image_mask = ImageOps.invert(image_mask)
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index a2c641dfab..49b829af89 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -90487,7 +90487,7 @@
"tags": ["image", "mask"],
"title": "Mask from Alpha",
"type": "object",
- "version": "1.2.2",
+ "version": "1.3.0",
"output": {
"$ref": "#/components/schemas/ImageOutput"
}
diff --git a/tests/app/invocations/test_image.py b/tests/app/invocations/test_image.py
index 08c5eb660d..a529bcdee2 100644
--- a/tests/app/invocations/test_image.py
+++ b/tests/app/invocations/test_image.py
@@ -7,7 +7,12 @@ import numpy
import torch
from PIL import Image, ImageFilter
-from invokeai.app.invocations.image import ImageField, OklabUnsharpMaskInvocation, OklchImageHueAdjustmentInvocation
+from invokeai.app.invocations.image import (
+ ImageField,
+ MaskFromAlphaInvocation,
+ OklabUnsharpMaskInvocation,
+ OklchImageHueAdjustmentInvocation,
+)
from invokeai.app.invocations.primitives import ImageCollectionInvocation
from invokeai.backend.image_util.color_conversion import (
linear_srgb_from_oklab,
@@ -49,6 +54,79 @@ def _max_abs_diff_uint8(left: Image.Image, right: Image.Image) -> int:
return int(numpy.abs(left_arr - right_arr).max())
+def _invoke_mask_from_alpha(input_image: Image.Image, invert: bool = False, expected_mode: str = "L") -> list[int]:
+ context = MagicMock()
+ # Like the real context, convert to the requested mode.
+ context.images.get_pil.side_effect = lambda image_name, mode=None: (
+ input_image.convert(mode) if mode else input_image.copy()
+ )
+ context.images.save.side_effect = lambda image, image_category: SimpleNamespace(
+ image_name="out", width=image.width, height=image.height
+ )
+
+ MaskFromAlphaInvocation(image=ImageField(image_name="in"), invert=invert).invoke(context)
+ saved_image = context.images.save.call_args.kwargs["image"]
+
+ assert saved_image.mode == expected_mode
+ return numpy.asarray(saved_image).reshape(-1).tolist()
+
+
+def test_mask_from_alpha_uses_the_alpha_channel() -> None:
+ input_image = Image.new("RGBA", (3, 1))
+ input_image.putdata([(10, 20, 30, 0), (10, 20, 30, 128), (10, 20, 30, 255)])
+
+ assert _invoke_mask_from_alpha(input_image) == [0, 128, 255]
+ assert _invoke_mask_from_alpha(input_image, invert=True) == [255, 127, 0]
+
+
+def test_mask_from_alpha_uses_the_alpha_channel_of_a_grayscale_image_with_alpha() -> None:
+ input_image = Image.new("LA", (3, 1))
+ input_image.putdata([(10, 0), (10, 128), (10, 255)])
+
+ assert _invoke_mask_from_alpha(input_image) == [0, 128, 255]
+ assert _invoke_mask_from_alpha(input_image, invert=True) == [255, 127, 0]
+
+
+def test_mask_from_alpha_uses_a_grayscale_image_as_the_mask() -> None:
+ input_image = Image.new("L", (3, 1))
+ input_image.putdata([0, 64, 200])
+
+ assert _invoke_mask_from_alpha(input_image) == [0, 64, 200]
+ assert _invoke_mask_from_alpha(input_image, invert=True) == [255, 191, 55]
+
+
+def test_mask_from_alpha_uses_a_one_bit_image_as_the_mask() -> None:
+ input_image = Image.new("1", (3, 1))
+ input_image.putdata([0, 255, 0])
+
+ assert _invoke_mask_from_alpha(input_image) == [0, 255, 0]
+ assert _invoke_mask_from_alpha(input_image, invert=True) == [255, 0, 255]
+
+
+def test_mask_from_alpha_uses_a_16_bit_grayscale_image_as_the_mask() -> None:
+ input_image = Image.fromarray(numpy.array([[0, 300, 40000]], dtype=numpy.uint16))
+ assert input_image.mode == "I;16"
+
+ assert _invoke_mask_from_alpha(input_image, expected_mode="I;16") == [0, 300, 40000]
+
+
+def test_mask_from_alpha_treats_an_rgb_image_as_opaque() -> None:
+ input_image = Image.new("RGB", (3, 1))
+ input_image.putdata([(255, 0, 0), (0, 255, 0), (0, 0, 64)])
+
+ assert _invoke_mask_from_alpha(input_image) == [255, 255, 255]
+ assert _invoke_mask_from_alpha(input_image, invert=True) == [0, 0, 0]
+
+
+def test_mask_from_alpha_uses_palette_transparency() -> None:
+ palette_image = Image.new("P", (3, 1))
+ palette_image.putpalette([0, 0, 0, 255, 255, 255])
+ palette_image.putdata([0, 1, 0])
+ palette_image.info["transparency"] = 0
+
+ assert _invoke_mask_from_alpha(palette_image) == [0, 255, 0]
+
+
def test_image_collection_invocation_preserves_existing_collection_values() -> None:
images = [ImageField(image_name="first"), ImageField(image_name="second")]