Skip to content

Commit

Permalink
Create "Premultiplied Alpha" Node (#2578)
Browse files Browse the repository at this point in the history
* Create "Premultiply Node"

This node premultiplies the RGB channels with the Alpha channel and produces an image with an "Associated pixel state". 

A lot of the graphics/workflows out there "assume" premultiplied RGBA channels so having this node available in chaiNNer's toolset will help it do more conversions that previously weren't possible in the application.

* Update premultiply.py

linting

* Delete backend/src/packages/chaiNNer_standard/image_adjustment/adjustments/premultiply.py

* Create "Premultiplied Alpha" node

This node allows the user to convert from a "Premultiplied" Alpha channel state to a "Straight/Unpremultiplied" alpha channel state, and vice versa.

* Update premultiplied_alpha.py

Try and just force dtype to float32 to clear the backend linter.

* Update premultiplied_alpha.py - Reworked

Reworked the PR to use the suggested naming and concepts.
  • Loading branch information
mrjschulte authored Feb 27, 2024
1 parent f827f35 commit 3be5841
Showing 1 changed file with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from __future__ import annotations

from enum import Enum

import numpy as np

from nodes.properties.inputs import EnumInput, ImageInput
from nodes.properties.outputs import ImageOutput

from .. import adjustments_group


class AlphaAssociation(Enum):
PREMULTIPLY_RGB = "Straight -> Premultiplied"
UNPREMULTIPLY_RGB = "Premultiplied -> Straight"


@adjustments_group.register(
schema_id="chainner:image:premultiplied_alpha",
description="Converts an RGBA Input from a Straight Alpha Association to a Premultiplied Alpha Association, or vice versa.",
name="Premultiplied Alpha",
icon="CgMathDivide",
inputs=[
ImageInput(channels=[4]),
EnumInput(
AlphaAssociation,
label="Alpha Association Conversion",
default=AlphaAssociation.PREMULTIPLY_RGB,
option_labels={
AlphaAssociation.PREMULTIPLY_RGB: "Straight → Premultiplied",
AlphaAssociation.UNPREMULTIPLY_RGB: "Premultiplied → Straight",
},
),
],
outputs=[ImageOutput(image_type="Input0")],
)
def premultiplied_alpha_node(
img: np.ndarray, alpha_association: AlphaAssociation
) -> np.ndarray:
rgb = img[..., :3]
alpha = img[..., 3]

if alpha_association == AlphaAssociation.UNPREMULTIPLY_RGB:
rgb_divided = rgb / alpha[..., np.newaxis]
return np.concatenate((rgb_divided, alpha[..., np.newaxis]), axis=-1)
elif alpha_association == AlphaAssociation.PREMULTIPLY_RGB:
rgb_multed = rgb * alpha[..., np.newaxis]
return np.concatenate((rgb_multed, alpha[..., np.newaxis]), axis=-1)
else:
raise ValueError(f"Invalid Alpha Association State '{alpha_association}'.")

0 comments on commit 3be5841

Please sign in to comment.