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(images): keep cached images independent of node-held objects (#10138)

Alexander Eichhorne28937b57539
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.py
index 82764a6cbe..08fea0daba 100644
--- a/invokeai/app/services/image_files/image_files_disk.py
+++ b/invokeai/app/services/image_files/image_files_disk.py
@@ -286,6 +286,10 @@ class DiskImageFileStorage(ImageFileStorageBase):
# PNG has no 32-bit integer mode, and Pillow 13 no longer clips "I" to 16 bits on save: do it here.
if image.mode == "I":
image = image.convert("I;16")
+ else:
+ # The object cached below must be ours alone: the caller keeps mutating its image, and the info
+ # assignment must not reach it.
+ image = image.copy()
# When saving the image, the image object's info field is not populated. We need to set it
image.info = info_dict
@@ -302,8 +306,7 @@ class DiskImageFileStorage(ImageFileStorageBase):
thumbnail_image.save(thumbnail_path)
- self.__set_cache(image_path, image)
- self.__set_cache(thumbnail_path, thumbnail_image)
+ self.__replace_cache({image_path: image, thumbnail_path: thumbnail_image})
except Exception as e:
# A thumbnail failure must not leave a full-size image with no thumbnail. The
# names are normally new, but preserve any pre-existing files when save() is
@@ -781,10 +784,28 @@ class DiskImageFileStorage(ImageFileStorageBase):
with self.__cache_lock:
if generation is not None and generation != self.__cache_generation:
return
- if image_name not in self.__cache:
- self.__cache[image_name] = image
- self.__cache_ids.put(image_name) # TODO: this should refresh position for LRU cache
- if len(self.__cache) > self.__max_cache_size:
- cache_id = self.__cache_ids.get()
- if cache_id in self.__cache:
- del self.__cache[cache_id]
+ if image_name in self.__cache:
+ return
+ self.__insert_cache_locked(image_name, image)
+
+ def __replace_cache(self, items: dict[Path, PILImageType]) -> None:
+ """Caches freshly written files, replacing entries of an earlier file under the same path.
+
+ The generation bump discards any `get` that read the old file and has not cached it yet. An existing
+ entry is overwritten in place, so its id is not queued twice.
+ """
+ with self.__cache_lock:
+ self.__cache_generation += 1
+ for path, image in items.items():
+ self.__insert_cache_locked(path, image)
+
+ def __insert_cache_locked(self, image_name: Path, image: PILImageType) -> None:
+ if image_name in self.__cache:
+ self.__cache[image_name] = image
+ return
+ self.__cache[image_name] = image
+ self.__cache_ids.put(image_name) # TODO: this should refresh position for LRU cache
+ if len(self.__cache) > self.__max_cache_size:
+ cache_id = self.__cache_ids.get()
+ if cache_id in self.__cache:
+ del self.__cache[cache_id]
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index a421a4420c..7543ccaaf3 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -373,6 +373,8 @@ class ImagesInterface(InvocationContextInterface):
self._services.logger.warning(
f"Could not convert image from {image.mode} to {mode}. Using original mode instead."
)
+ # the service hands out its cached object: the fallback must not return it
+ image = image.copy()
else:
# copy the image to prevent the user from modifying the original
image = image.copy()
diff --git a/pyproject.toml b/pyproject.toml
index e00fdab21b..5ca4e81a28 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -693,6 +693,7 @@ exclude = [
"invokeai/backend/image_util/normal_bae/", # External code
"invokeai/backend/image_util/pidi/", # External code
"invokeai/backend/image_util/imwatermark/", # External code
+ "tests/app/invocations/third_party_cinematic_effects/", # External code, kept unmodified
]
[tool.ruff.lint]
diff --git a/tests/app/invocations/test_third_party_image_nodes.py b/tests/app/invocations/test_third_party_image_nodes.py
new file mode 100644
index 0000000000..fb6ab76daa
--- /dev/null
+++ b/tests/app/invocations/test_third_party_image_nodes.py
@@ -0,0 +1,254 @@
+"""Third-party PIL custom nodes keep working through the real invocation image interface.
+
+The fixture in `third_party_cinematic_effects/` is six unmodified nodes of JPPhoto's cinematic-effects pack (see its
+PROVENANCE.md). They are registered the way the custom-node loader registers a pack, then run through real image
+services over a temporary SQLite database and temporary disk storage: `context.images.get_pil` -> PIL work ->
+`context.images.save` -> `ImageOutput`. Nothing is downloaded; Lens Blur gets a depth map and an aperture image
+supplied, so its depth model is never requested.
+"""
+
+import importlib.util
+import sys
+import types
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+from PIL import Image, ImageChops, ImageDraw
+
+from invokeai.app.invocations.baseinvocation import BaseInvocation, InvocationRegistry
+from invokeai.app.invocations.fields import ImageField
+from invokeai.app.invocations.image import BlankImageInvocation
+from invokeai.app.invocations.primitives import ImageOutput
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.names.names_default import SimpleNameService
+from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
+from invokeai.app.services.shared.graph import Graph, GraphExecutionState
+from invokeai.app.services.shared.invocation_context import (
+ InvocationContext,
+ InvocationContextData,
+ build_invocation_context,
+)
+from invokeai.app.services.urls.urls_default import LocalUrlService
+
+PACK_DIR = Path(__file__).parent / "third_party_cinematic_effects" / "cinematic_effects"
+# The pack is imported under a name of its own: the first segment of a module name is the node pack name.
+PACK_NAME = "jpphoto_cinematic_effects_fixture"
+# module -> (invocation type, class name)
+NODE_MODULES = {
+ "chromatic_aberration": ("chromatic_aberration", "ChromaticAberrationInvocation"),
+ "lens_vignette": ("lens_vignette", "LensVignetteInvocation"),
+ "lens_blur": ("lens_blur", "LensBlurInvocation"),
+ "curves": ("curves_invocation", "CurvesInvocation"),
+ "film_grain": ("film_grain", "FilmGrainInvocation"),
+ "spherical_distortion": ("spherical_distortion", "SphericalDistortionInvocation"),
+}
+SIZE = (64, 48)
+
+
[email protected](scope="module")
+def pack() -> Iterator[dict[str, type[BaseInvocation]]]:
+ """Loads the fixture nodes as the custom-node loader loads a pack, and removes them again afterwards."""
+ registered_before = set(InvocationRegistry.get_invocation_types())
+
+ package = types.ModuleType(PACK_NAME)
+ package.__path__ = [str(PACK_DIR)]
+ sys.modules[PACK_NAME] = package
+ try:
+ # util is imported by relative path from the nodes
+ for name in ("util", *NODE_MODULES):
+ spec = importlib.util.spec_from_file_location(f"{PACK_NAME}.{name}", PACK_DIR / f"{name}.py")
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ # film_grain.py registers more than one type, so look at what the pack actually registered.
+ loaded = {
+ c.get_type() for c in InvocationRegistry.get_invocation_classes() if c.UIConfig.node_pack == PACK_NAME
+ }
+ assert not loaded & registered_before, "a fixture node type replaced an already registered node"
+ yield {
+ invocation_type: getattr(sys.modules[f"{PACK_NAME}.{module}"], class_name)
+ for module, (invocation_type, class_name) in NODE_MODULES.items()
+ }
+ finally:
+ InvocationRegistry.unregister_pack(PACK_NAME)
+ for name in [name for name in sys.modules if name == PACK_NAME or name.startswith(f"{PACK_NAME}.")]:
+ del sys.modules[name]
+
+
+def invoker(mock_invoker: Invoker, tmp_path: Path) -> Invoker:
+ """Real image records (in-memory SQLite), real disk storage under tmp_path, real image service."""
+ services = mock_invoker.services
+ services.image_files = DiskImageFileStorage(tmp_path / "images")
+ services.names = SimpleNameService()
+ services.urls = LocalUrlService()
+ services.image_files.start(mock_invoker)
+ services.images.start(mock_invoker)
+ return mock_invoker
+
+
+def _source_image(mode: str) -> Image.Image:
+ """Coloured blocks over a gradient, with a varying alpha: every node has something to change."""
+ width, height = SIZE
+ x = np.linspace(0, 255, width, dtype=np.uint8)[None, :].repeat(height, axis=0)
+ y = np.linspace(0, 255, height, dtype=np.uint8)[:, None].repeat(width, axis=1)
+ rgb = Image.fromarray(np.stack([x, y, 255 - x], axis=2), "RGB")
+ draw = ImageDraw.Draw(rgb)
+ for left in range(0, width, 16):
+ draw.rectangle((left, 8, left + 7, 39), fill=(255, 255, 255) if left % 32 == 0 else (10, 10, 10))
+ image = rgb.convert("RGBA")
+ image.putalpha(Image.fromarray(np.linspace(100, 255, width, dtype=np.uint8)[None, :].repeat(height, axis=0)))
+ return image.convert(mode)
+
+
+def _store(invoker: Invoker, image: Image.Image) -> str:
+ return invoker.services.images.create(
+ image=image, image_origin=ResourceOrigin.INTERNAL, image_category=ImageCategory.GENERAL
+ ).image_name
+
+
+def _context_for(invoker: Invoker, node: BaseInvocation) -> tuple[BaseInvocation, InvocationContext]:
+ """The prepared invocation and real context the session runner would hand to `invoke`."""
+ graph = Graph()
+ graph.add_node(node)
+ session = GraphExecutionState(graph=graph)
+ queue_item = SessionQueueItem(
+ item_id=1,
+ batch_id="batch",
+ session_id=session.id,
+ created_at="2026-01-01T00:00:00",
+ updated_at="2026-01-01T00:00:00",
+ started_at=None,
+ completed_at=None,
+ queue_id="default",
+ session=session,
+ )
+ invocation = session.next()
+ assert invocation is not None
+ context = build_invocation_context(
+ services=invoker.services,
+ data=InvocationContextData(queue_item=queue_item, invocation=invocation, source_invocation_id=node.id),
+ is_canceled=lambda: False,
+ )
+ return invocation, context
+
+
+def _run(invoker: Invoker, node: BaseInvocation) -> ImageOutput:
+ invocation, context = _context_for(invoker, node)
+ output = invocation.invoke(context)
+ assert isinstance(output, ImageOutput)
+ return output
+
+
+def _lens_blur_inputs(invoker: Invoker) -> dict[str, Any]:
+ depth = Image.fromarray(np.linspace(0, 255, SIZE[0], dtype=np.uint8)[None, :].repeat(SIZE[1], axis=0), "L")
+ aperture = Image.new("L", (512, 512), 0)
+ ImageDraw.Draw(aperture).ellipse((56, 56, 456, 456), fill=255)
+ return {
+ "depth_map": ImageField(image_name=_store(invoker, depth)),
+ # Optional in the declaration, but the node dereferences it unconditionally.
+ "aperture_image": ImageField(image_name=_store(invoker, aperture)),
+ "focal_distance": 0.0,
+ "distance_range": 0.2,
+ "max_blur_radius": 4.0,
+ "max_blur_steps": 4,
+ "reduce_halos": False,
+ }
+
+
+# (node type, input mode, output mode, alpha, extra fields). Alpha is "kept" (identical to the source), "opaque"
+# (discarded: Lens Blur and Film Grain convert their RGB result back to the input mode, which makes it fully opaque;
+# that is how the pack behaves today and is recorded as such) or "warped" (moved along with the pixels).
+# Curves widens L to RGB and LA to RGBA.
+CURVES = {"mapping_str": "0:0,128:40,255:255"}
+CASES = [
+ ("chromatic_aberration", "RGB", "RGB", None, {"strength": 6.0}),
+ ("chromatic_aberration", "RGBA", "RGBA", "kept", {"strength": 6.0}),
+ ("lens_vignette", "RGB", "RGB", None, {"intensity": 2.0}),
+ ("lens_vignette", "RGBA", "RGBA", "kept", {"intensity": 2.0}),
+ ("lens_blur", "RGB", "RGB", None, {}),
+ ("lens_blur", "RGBA", "RGBA", "opaque", {}),
+ ("curves_invocation", "RGB", "RGB", None, CURVES),
+ ("curves_invocation", "RGBA", "RGBA", "kept", CURVES),
+ ("curves_invocation", "L", "RGB", None, CURVES),
+ ("curves_invocation", "LA", "RGBA", "kept", CURVES),
+ ("film_grain", "RGB", "RGB", None, {"seed_1": 1, "seed_2": 2}),
+ ("film_grain", "RGBA", "RGBA", "opaque", {"seed_1": 1, "seed_2": 2}),
+ ("spherical_distortion", "RGB", "RGB", None, {"k1": 0.4}),
+ ("spherical_distortion", "RGBA", "RGBA", "warped", {"k1": 0.4}),
+]
+
+
+def test_all_six_nodes_register(pack: dict[str, type[BaseInvocation]]) -> None:
+ for invocation_type, node_class in pack.items():
+ assert InvocationRegistry.get_invocation_for_type(invocation_type) is node_class
+ assert node_class.UIConfig.node_pack == PACK_NAME
+
+
[email protected](("invocation_type", "mode", "result_mode", "alpha_outcome", "fields"), CASES)
+def test_node_saves_a_readable_changed_image(
+ pack: dict[str, type[BaseInvocation]],
+ invoker: Invoker,
+ invocation_type: str,
+ mode: str,
+ result_mode: str,
+ alpha_outcome: str | None,
+ fields: dict[str, Any],
+) -> None:
+ source = _source_image(mode)
+ source_name = _store(invoker, source)
+ stored_source = invoker.services.images.get_pil_image(source_name)
+ if invocation_type == "lens_blur":
+ fields = {**fields, **_lens_blur_inputs(invoker)}
+
+ node = pack[invocation_type](id="node", image=ImageField(image_name=source_name), **fields)
+ output = _run(invoker, node)
+
+ result = invoker.services.images.get_pil_image(output.image.image_name)
+ assert invoker.services.images.get_dto(output.image.image_name).image_name == output.image.image_name
+ assert (output.width, output.height) == result.size
+ assert result.mode == result_mode
+ if invocation_type != "spherical_distortion":
+ # Spherical Distortion crops to the distorted content; the others keep the frame.
+ assert result.size == SIZE
+ # The effect moved colour/luma pixels (alpha is compared separately).
+ colour_before, colour_after = stored_source.convert("RGB"), result.convert("RGB")
+ assert colour_before.size != colour_after.size or ImageChops.difference(colour_before, colour_after).getbbox()
+
+ if alpha_outcome is not None:
+ alpha = result.getchannel("A")
+ if alpha_outcome == "kept":
+ assert ImageChops.difference(alpha, stored_source.getchannel("A")).getbbox() is None
+ elif alpha_outcome == "opaque":
+ assert alpha.getextrema() == (255, 255)
+ else:
+ assert alpha.getextrema()[0] < 255
+
+
+def test_lens_blur_aperture_is_required_in_practice(pack: dict[str, type[BaseInvocation]], invoker: Invoker) -> None:
+ """Baseline: `aperture_image` is declared optional, yet the node reads it unconditionally."""
+ fields = _lens_blur_inputs(invoker)
+ del fields["aperture_image"]
+ node = pack["lens_blur"](id="node", image=ImageField(image_name=_store(invoker, _source_image("RGB"))), **fields)
+
+ with pytest.raises(AttributeError):
+ _run(invoker, node)
+
+
+def test_get_pil_results_are_independent_of_the_service_cache(invoker: Invoker) -> None:
+ """Whatever a node does to the image `get_pil` hands out, the next read sees the stored pixels."""
+ name = _store(invoker, _source_image("RGB"))
+ expected = invoker.services.images.get_pil_image(name).tobytes()
+ _, context = _context_for(invoker, BlankImageInvocation(id="node"))
+
+ for mode in (None, "RGB", "L"):
+ mutated = context.images.get_pil(name, mode)
+ mutated.paste((1, 2, 3) if mutated.mode == "RGB" else 7, (0, 0, *SIZE))
+ assert context.images.get_pil(name).tobytes() == expected
+ assert invoker.services.images.get_pil_image(name).tobytes() == expected
diff --git a/tests/app/invocations/third_party_cinematic_effects/LICENSE b/tests/app/invocations/third_party_cinematic_effects/LICENSE
new file mode 100644
index 0000000000..4621c58227
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2023 Jonathan
+Copyright (c) 2024-2025 Jonathan S. Pollack
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tests/app/invocations/third_party_cinematic_effects/PROVENANCE.md b/tests/app/invocations/third_party_cinematic_effects/PROVENANCE.md
new file mode 100644
index 0000000000..2f63fd91da
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/PROVENANCE.md
@@ -0,0 +1,15 @@
+# Provenance
+
+Unmodified copies of third-party InvokeAI custom nodes, used to check that code written against
+`context.images.get_pil` / `context.images.save` keeps working.
+
+- Source: https://github.com/JPPhoto/cinematic-effects-pack
+- Commit: 4a4dfa77ec8c57968281f8162a685d1d89a1aaea
+- License: MIT (`LICENSE`, Copyright Jonathan S. Pollack)
+- Files, copied byte for byte into `cinematic_effects/` (six node files registering eight invocation types,
+ because `film_grain.py` also registers `monochrome_film_grain` and `chroma_noise`, plus one helper module):
+ `chromatic_aberration.py`, `lens_vignette.py`, `lens_blur.py`, `curves.py`, `film_grain.py`,
+ `spherical_distortion.py`, and `util.py` (imported by lens_vignette, lens_blur and curves).
+
+The pack's `__init__.py` is not copied: it imports nodes this fixture does not carry.
+Do not edit these files; bump the commit and re-copy instead.
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/chromatic_aberration.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/chromatic_aberration.py
new file mode 100644
index 0000000000..fd9e7016fa
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/chromatic_aberration.py
@@ -0,0 +1,92 @@
+# Copyright (c) 2025 Jonathan S. Pollack (https://github.com/JPPhoto)
+
+import numpy as np
+from invokeai.invocation_api import (
+ BaseInvocation,
+ ImageField,
+ ImageOutput,
+ InputField,
+ InvocationContext,
+ WithBoard,
+ WithMetadata,
+ invocation,
+)
+from PIL import Image
+from scipy.ndimage import map_coordinates
+
+
+@invocation(
+ "chromatic_aberration",
+ title="Chromatic Aberration",
+ tags=["image", "postprocessing", "chromatic", "aberration"],
+ version="1.1.0",
+)
+class ChromaticAberrationInvocation(BaseInvocation, WithBoard, WithMetadata):
+ """Simulate realistic chromatic aberration in an image with controllable strength and center point."""
+
+ image: ImageField = InputField(description="The image to apply chromatic aberration to")
+ strength: float = InputField(default=1.0, ge=0.0, le=10.0, description="Strength of the chromatic shift (0–10)")
+ center_x: float = InputField(default=0.5, ge=0.0, le=1.0, description="X coordinate of center (0–1)")
+ center_y: float = InputField(default=0.5, ge=0.0, le=1.0, description="Y coordinate of center (0–1)")
+
+ def srgb_to_linear(self, srgb: np.ndarray) -> np.ndarray:
+ """Convert sRGB gamma-encoded to linear RGB."""
+ a = 0.055
+ return np.where(srgb <= 0.04045, srgb / 12.92, ((srgb + a) / (1 + a)) ** 2.4)
+
+ def linear_to_srgb(self, linear: np.ndarray) -> np.ndarray:
+ """Convert linear RGB to sRGB gamma-encoded."""
+ a = 0.055
+ return np.where(linear <= 0.0031308, 12.92 * linear, (1 + a) * np.power(np.maximum(linear, 0.0), 1 / 2.4) - a)
+
+ def radial_offset(self, channel, dx, dy, strength) -> np.ndarray:
+ """Offset a single color channel radially outward or inward."""
+ height, width = channel.shape
+ y, x = np.meshgrid(np.arange(height), np.arange(width), indexing="ij")
+ norm = np.sqrt(dx**2 + dy**2)
+ shift_x = x + dx / (norm + 1e-6) * strength
+ shift_y = y + dy / (norm + 1e-6) * strength
+
+ coords = [np.clip(shift_y, 0, height - 1), np.clip(shift_x, 0, width - 1)]
+ return map_coordinates(channel, coords, order=1, mode="reflect")
+
+ def apply_chromatic_aberration(self, image: Image.Image) -> Image.Image:
+ """Apply chromatic aberration in linear RGB space."""
+ img = np.array(image).astype(np.float32) / 255.0
+ if img.shape[2] == 4:
+ rgb, alpha = img[..., :3], img[..., 3:]
+ else:
+ rgb, alpha = img, None
+
+ # Convert to linear RGB
+ rgb_linear = self.srgb_to_linear(rgb)
+
+ height, width = rgb.shape[:2]
+ cx = self.center_x * width
+ cy = self.center_y * height
+
+ dx = np.tile(np.arange(width)[None, :] - cx, (height, 1))
+ dy = np.tile(np.arange(height)[:, None] - cy, (1, width))
+
+ strength = self.strength
+
+ red = self.radial_offset(rgb_linear[..., 0], dx, dy, strength)
+ green = self.radial_offset(rgb_linear[..., 1], dx, dy, strength * 0.5)
+ blue = self.radial_offset(rgb_linear[..., 2], dx, dy, -strength)
+
+ out_rgb_linear = np.stack([red, green, blue], axis=-1)
+ out_rgb = np.clip(self.linear_to_srgb(out_rgb_linear), 0.0, 1.0)
+
+ if alpha is not None:
+ out = np.concatenate([out_rgb, alpha], axis=2)
+ else:
+ out = out_rgb
+
+ result = (out * 255.0).clip(0, 255).astype(np.uint8)
+ return Image.fromarray(result)
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ pil_image = context.images.get_pil(self.image.image_name)
+ result_image = self.apply_chromatic_aberration(pil_image)
+ image_dto = context.images.save(image=result_image)
+ return ImageOutput.build(image_dto)
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/curves.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/curves.py
new file mode 100644
index 0000000000..e9475b8475
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/curves.py
@@ -0,0 +1,281 @@
+# Copyright (c) 2025 Jonathan S. Pollack (https://github.com/JPPhoto)
+
+import re
+from typing import Literal
+
+import numpy as np
+from invokeai.invocation_api import (
+ BaseInvocation,
+ ImageField,
+ ImageOutput,
+ InputField,
+ InvocationContext,
+ WithBoard,
+ WithMetadata,
+ invocation,
+)
+from PIL import Image
+from scipy.interpolate import CubicSpline, PchipInterpolator
+
+from .util import oklch_to_rgb, rgb_to_oklch # noqa: TID252
+
+_INTERPOLATION_METHODS = {"lin": "linear", "cat": "catmull_rom", "cub": "cubic", "pch": "pchip"}
+
+
+@invocation(
+ "curves_invocation", title="CurvesInvocation", tags=["curves", "interpolation", "dithering"], version="1.3.0"
+)
+class CurvesInvocation(BaseInvocation, WithMetadata, WithBoard):
+ """Applies interpolation and dithering to an image based on user inputs"""
+
+ image: ImageField = InputField(description="The image to apply curves and dithering to")
+ mapping_str: str = InputField(
+ description="String of input-output mappings", default="0:0,64:48,128:128,200:240,255:255"
+ )
+ interpolation_method: Literal["catmull_rom", "linear", "cubic", "pchip"] = InputField(
+ default="catmull_rom", description="Interpolation method"
+ )
+ dithering_method: Literal["none", "blue_noise", "floyd_steinberg", "ordered"] = InputField(
+ default="blue_noise", description="Dithering method"
+ )
+ channel: Literal["RGB", "R", "G", "B", "L (OKLCH)"] = InputField(default="RGB", description="Channel to alter")
+
+ def parse_mapping(self, mapping_str: str) -> list[tuple[int, int]]:
+ """Parses a string of mappings into a list of (input, output) pairs."""
+ pairs = mapping_str.replace(" ", "").split(",")
+ pts: list[tuple[int, int]] = []
+ for pair in pairs:
+ i, o = pair.split(":")
+ pts.append((int(i), int(o)))
+ return pts
+
+ def denormalize_image(self, img_array: np.ndarray) -> np.ndarray:
+ """Denormalize the image back to [0, 255] range."""
+ return np.clip(img_array * 255.0, 0, 255).astype(np.uint8)
+
+ def catmull_rom_spline(self, x: float, points: list[tuple[float, float]]) -> float:
+ """Performs Catmull-Rom spline interpolation given a set of points."""
+ pts = sorted(points, key=lambda p: p[0])
+ n = len(pts)
+ if x <= pts[0][0]:
+ result = pts[0][1]
+ elif x >= pts[-1][0]:
+ result = pts[-1][1]
+ else:
+ j = next(i for i in range(n - 1) if pts[i][0] <= x <= pts[i + 1][0])
+ p1 = pts[j]
+ p2 = pts[j + 1]
+ p0 = pts[j - 1] if j - 1 >= 0 else p1
+ p3 = pts[j + 2] if j + 2 < n else p2
+ t = (x - p1[0]) / (p2[0] - p1[0])
+ a0 = -0.5 * p0[1] + 1.5 * p1[1] - 1.5 * p2[1] + 0.5 * p3[1]
+ a1 = p0[1] - 2.5 * p1[1] + 2 * p2[1] - 0.5 * p3[1]
+ a2 = -0.5 * p0[1] + 0.5 * p2[1]
+ a3 = p1[1]
+ result = a0 * t**3 + a1 * t**2 + a2 * t + a3
+ return result
+
+ def linear_interpolation(self, x: float, points: list[tuple[float, float]]) -> float:
+ """Performs linear interpolation between two points."""
+ pts = sorted(points, key=lambda p: p[0])
+ for i in range(1, len(pts)):
+ if x < pts[i][0]:
+ x0, y0 = pts[i - 1]
+ x1, y1 = pts[i]
+ return y0 + (x - x0) * (y1 - y0) / (x1 - x0)
+ return pts[-1][1]
+
+ def apply_interpolation(self, channel: np.ndarray, points: list[tuple[int, int]], method: str) -> np.ndarray:
+ """Apply interpolation to a single-channel (2D) image array."""
+ # normalize control points once
+ pts = [(xi / 255.0, yi / 255.0) for xi, yi in points]
+ if method in ("cubic", "pchip"):
+ pts = sorted(pts, key=lambda p: p[0])
+ xs, ys = zip(*pts)
+ interpolator = CubicSpline if method == "cubic" else PchipInterpolator
+ return interpolator(xs, ys)(channel).astype(np.float32)
+
+ h, w = channel.shape
+ out = np.empty((h, w), dtype=np.float32)
+ for y in range(h):
+ row = channel[y]
+ for x in range(w):
+ v = float(row[x]) # already in [0,1]
+ if method == "catmull_rom":
+ out[y, x] = self.catmull_rom_spline(v, pts)
+ elif method == "linear":
+ out[y, x] = self.linear_interpolation(v, pts)
+ else:
+ raise ValueError(f"Unsupported interpolation: {method}")
+
+ return out
+
+ def no_dither(self, channel: np.ndarray) -> np.ndarray:
+ """A no-op conversion"""
+ return np.clip(channel, 0.0, 1.0)
+
+ def floyd_steinberg_dither(self, channel: np.ndarray) -> np.ndarray:
+ """Optimized Floyd–Steinberg dithering with 8-bit quantization using NumPy."""
+ d = channel.astype(np.float32).copy()
+ h, w = d.shape
+
+ # Precomputed weights
+ w1, w2, w3, w4 = 7 / 16, 3 / 16, 5 / 16, 1 / 16
+
+ for y in range(h - 1):
+ for x in range(1, w - 1):
+ old = d[y, x]
+ new = round(old * 255) / 255
+ if old != new:
+ err = old - new
+ d[y, x] = new
+
+ # Propagate error
+ d[y, x + 1] += err * w1
+ d[y + 1, x - 1] += err * w2
+ d[y + 1, x] += err * w3
+ d[y + 1, x + 1] += err * w4
+ return np.clip(d, 0.0, 1.0)
+
+ def generate_bayer_matrix(self, n: int) -> np.ndarray:
+ """Generates an N×N Bayer matrix normalized to [0, 1), where N is a power of 2."""
+ assert (n & (n - 1)) == 0 and n > 0, "Size must be a power of 2"
+
+ def build(k: int) -> np.ndarray:
+ if k == 1:
+ return np.array([[0]])
+ prev = build(k // 2)
+ tiled = np.block([[4 * prev + 0, 4 * prev + 2], [4 * prev + 3, 4 * prev + 1]])
+ return tiled
+
+ mat = build(n)
+ return mat / (n * n)
+
+ def ordered_dither(self, channel: np.ndarray) -> np.ndarray:
+ """Vectorized ordered dithering with 8-bit quantization using a Bayer matrix."""
+ threshold = self.generate_bayer_matrix(256)
+ h, w = channel.shape
+ th_h, th_w = threshold.shape
+ tile = np.tile(threshold, (h // th_h + 1, w // th_w + 1))[:h, :w]
+ quantized = np.clip(np.round(channel * 255 + (tile - 0.5)) / 255, 0.0, 1.0)
+ return quantized
+
+ def blue_noise_dither(self, channel: np.ndarray) -> np.ndarray:
+ """Applies blue-noise-like dithering using a locally shuffled Bayer matrix approximation."""
+ h, w = channel.shape
+
+ # Step 1: Generate a large Bayer matrix
+ base = self.generate_bayer_matrix(256) # In [0,1)
+
+ # Step 2: Localized random shuffle
+ rng = np.random.default_rng(seed=0) # Remove seed for non-deterministic noise
+ flat = base.flatten()
+ shuffled = rng.permutation(flat) # Local, reproducible shuffle
+ blue_noise = shuffled.reshape(base.shape)
+
+ # Step 3: Tile to match input size
+ tile = np.tile(blue_noise, (h // 64 + 1, w // 64 + 1))[:h, :w]
+
+ # Step 4: Apply dithering
+ quantized = np.clip(np.round(channel * 255 + (tile - 0.5)) / 255, 0.0, 1.0)
+ return quantized
+
+ def apply_dithering(self, channel: np.ndarray) -> np.ndarray:
+ """Apply dithering to a single-channel array using the selected method."""
+ if self.dithering_method == "none":
+ return self.no_dither(channel)
+ elif self.dithering_method == "blue_noise":
+ return self.blue_noise_dither(channel)
+ elif self.dithering_method == "floyd_steinberg":
+ return self.floyd_steinberg_dither(channel)
+ elif self.dithering_method == "ordered":
+ return self.ordered_dither(channel)
+ else:
+ raise ValueError(f"Unsupported dithering: {self.dithering_method}")
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.get_pil(self.image.image_name)
+ mode = image.mode
+
+ # extract alpha
+ if mode == "RGBA":
+ alpha = np.array(image.split()[3])
+ image = image.convert("RGB")
+ elif mode == "LA":
+ alpha = np.array(image.split()[1])
+ image = image.convert("L")
+ else:
+ alpha = None
+
+ ops = self._parse_adjustments(self.mapping_str)
+ if not ops:
+ ops = [(None, None, self.parse_mapping(self.mapping_str))] # Legacy fallback
+
+ arr_rgb = np.asarray(image.convert("RGB")).astype(np.float32) / 255.0
+
+ for ch_spec, method_abbrev, pts in ops:
+ channel = ch_spec or self.channel
+ if channel == "L":
+ channel = "L (OKLCH)"
+
+ if method_abbrev is None:
+ method = self.interpolation_method
+ else:
+ method = _INTERPOLATION_METHODS.get(method_abbrev)
+
+ if channel == "L (OKLCH)":
+ oklch = rgb_to_oklch(arr_rgb)
+ L = oklch[..., 0]
+ interp = self.apply_interpolation(L, pts, method)
+ oklch[..., 0] = interp
+ arr_rgb = oklch_to_rgb(oklch)
+ elif channel in ["R", "G", "B"]:
+ ch_index = {"R": 0, "G": 1, "B": 2}[channel]
+ interp = self.apply_interpolation(arr_rgb[..., ch_index], pts, method)
+ arr_rgb[..., ch_index] = interp
+ else: # RGB, all channels
+ interp = np.stack(
+ [self.apply_interpolation(arr_rgb[..., c], pts, method) for c in range(arr_rgb.shape[2])],
+ axis=-1,
+ )
+ arr_rgb = interp
+
+ dithered = np.stack(
+ [self.apply_dithering(arr_rgb[..., c]) for c in range(arr_rgb.shape[2])],
+ axis=-1,
+ )
+ result = self.denormalize_image(dithered)
+
+ # reassemble
+ if alpha is not None:
+ final = Image.fromarray(np.dstack([result, alpha]))
+ else:
+ final = Image.fromarray(result)
+
+ dto = context.images.save(image=final)
+ return ImageOutput.build(dto)
+
+ def _parse_adjustments(self, s: str) -> list[tuple[list[str] | None, str | None, list[tuple[int, int]]]]:
+ """
+ Parses operations:
+ - New form: R[cat](0:0,128:150,255:255) G(0:0,128:130,255:250) RGB[lin](...)
+ - Legacy: 0:0,64:48,128:128,200:240,255:255
+ Returns list of (channels, method_abbrev, points)
+ channels -> ['R'] or ['R','G','B'] or None (use defaults)
+ """
+ s = s.strip()
+ ops: list[tuple[list[str] | None, str | None, list[tuple[int, int]]]] = []
+ pat = re.compile(r"(?:(RGB|R|G|B|L)(?:\[(lin|cat|cub|pch)\])?)?\(([^)]*)\)")
+ matches = list(pat.finditer(s))
+ if matches:
+ for m in matches:
+ channel = m.group(1)
+ method = m.group(2)
+ pts_str = m.group(3)
+ pts = self.parse_mapping(pts_str)
+ ops.append((channel, method, pts))
+ return ops
+ # legacy bare mapping (backward-compat)
+ if ":" in s:
+ ops.append((None, None, self.parse_mapping(s)))
+ return ops
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/film_grain.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/film_grain.py
new file mode 100644
index 0000000000..d48a3eb032
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/film_grain.py
@@ -0,0 +1,261 @@
+# Copyright (c) 2024 Jonathan S. Pollack (https://github.com/JPPhoto)
+
+from typing import Optional
+
+import numpy as np
+from invokeai.invocation_api import (
+ SEED_MAX,
+ BaseInvocation,
+ ImageField,
+ ImageOutput,
+ InputField,
+ InvocationContext,
+ WithBoard,
+ WithMetadata,
+ get_random_seed,
+ invocation,
+)
+from PIL import Image, ImageChops, ImageFilter
+
+
+@invocation("film_grain", title="FilmGrain", tags=["film_grain"], version="1.2.0")
+class FilmGrainInvocation(BaseInvocation, WithMetadata, WithBoard):
+ """Adds film grain to an image"""
+
+ image: ImageField = InputField(description="The image to add film grain to")
+ amount_1: int = InputField(ge=0, le=800, description="Amount of the first noise layer", default=100)
+ amount_2: int = InputField(ge=0, le=800, description="Amount of the second noise layer", default=50)
+ seed_1: Optional[int] = InputField(ge=0, le=SEED_MAX, description="The first seed to use (omit for random)")
+ seed_2: Optional[int] = InputField(ge=0, le=SEED_MAX, description="The second seed to use (omit for random)")
+ blur_1: float = InputField(ge=0, le=100, description="The strength of the first noise blur", default=0.5)
+ blur_2: float = InputField(ge=0, le=100, description="The strength of the second noise blur", default=0.5)
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.get_pil(self.image.image_name)
+ mode = image.mode
+
+ if mode == "RGBA":
+ image = image.convert("RGB")
+
+ rng = np.random.default_rng(seed=self.seed_1 if self.seed_1 is not None else get_random_seed())
+ noise_1 = rng.normal(0, 1, (image.size[1], image.size[0], 3)) * 127.5 * (self.amount_1 / 800.0)
+ noise_1 = noise_1 + 127.5
+ noise_1 = Image.fromarray(noise_1.astype("uint8"))
+ noise_1 = noise_1.filter(ImageFilter.GaussianBlur(radius=self.blur_1))
+
+ rng = np.random.default_rng(seed=self.seed_2 if self.seed_2 is not None else get_random_seed())
+ noise_2 = rng.normal(0, 1, (image.size[1], image.size[0], 3)) * 127.5 * (self.amount_2 / 800.0)
+ noise_2 = noise_2 + 127.5
+ noise_2 = Image.fromarray(noise_2.astype("uint8"))
+ noise_2 = noise_2.filter(ImageFilter.GaussianBlur(radius=self.blur_2))
+
+ image = ImageChops.overlay(image, noise_1)
+ image = ImageChops.overlay(image, noise_2)
+
+ if mode == "RGBA":
+ image = image.convert("RGBA")
+
+ image_dto = context.images.save(image=image)
+
+ return ImageOutput.build(image_dto)
+
+
+@invocation("monochrome_film_grain", title="MonochromeFilmGrain", tags=["film_grain", "monochrome"], version="1.2.0")
+class MonochromeFilmGrainInvocation(BaseInvocation, WithMetadata, WithBoard):
+ """Adds monochrome film grain to an image"""
+
+ image: ImageField = InputField(description="The image to add film grain to")
+ amount_1: int = InputField(ge=0, le=800, description="Amount of the first noise layer", default=100)
+ amount_2: int = InputField(ge=0, le=800, description="Amount of the second noise layer", default=50)
+ seed_1: Optional[int] = InputField(ge=0, le=SEED_MAX, description="The first seed to use (omit for random)")
+ seed_2: Optional[int] = InputField(ge=0, le=SEED_MAX, description="The second seed to use (omit for random)")
+ blur_1: float = InputField(ge=0, le=100, description="The strength of the first noise blur", default=0.5)
+ blur_2: float = InputField(ge=0, le=100, description="The strength of the second noise blur", default=0.5)
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.get_pil(self.image.image_name)
+ mode = image.mode
+
+ if mode == "RGBA":
+ image = image.convert("RGB")
+
+ rng = np.random.default_rng(seed=self.seed_1 if self.seed_1 is not None else get_random_seed())
+ noise_1 = rng.normal(0, 1, (image.size[1], image.size[0])) * 127.5 * (self.amount_1 / 800.0)
+ noise_1 = noise_1 + 127.5
+ noise_1 = Image.fromarray(noise_1.astype("uint8"))
+ noise_1 = noise_1.filter(ImageFilter.GaussianBlur(radius=self.blur_1))
+ noise_1 = noise_1.convert("RGB")
+
+ rng = np.random.default_rng(seed=self.seed_2 if self.seed_2 is not None else get_random_seed())
+ noise_2 = rng.normal(0, 1, (image.size[1], image.size[0])) * 127.5 * (self.amount_2 / 800.0)
+ noise_2 = noise_2 + 127.5
+ noise_2 = Image.fromarray(noise_2.astype("uint8"))
+ noise_2 = noise_2.filter(ImageFilter.GaussianBlur(radius=self.blur_2))
+ noise_2 = noise_2.convert("RGB")
+
+ image = ImageChops.overlay(image, noise_1)
+ image = ImageChops.overlay(image, noise_2)
+
+ if mode == "RGBA":
+ image = image.convert("RGBA")
+
+ image_dto = context.images.save(image=image)
+
+ return ImageOutput.build(image_dto)
+
+
+@invocation("chroma_noise", title="ChromaNoise", tags=["film_grain", "chroma_noise"], version="1.2.0")
+class ChromaNoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
+ """Adds chroma-only noise (in OKLab space) to an image."""
+
+ image: ImageField = InputField(description="The image to add chroma noise to")
+ amount_1: int = InputField(ge=0, le=800, description="Amount of the first chroma noise layer", default=100)
+ amount_2: int = InputField(ge=0, le=800, description="Amount of the second chroma noise layer", default=50)
+ seed_1: Optional[int] = InputField(ge=0, le=SEED_MAX, description="The first seed to use (omit for random)")
+ seed_2: Optional[int] = InputField(ge=0, le=SEED_MAX, description="The second seed to use (omit for random)")
+ blur_1: float = InputField(ge=0, le=100, description="The strength of the first noise blur", default=0.5)
+ blur_2: float = InputField(ge=0, le=100, description="The strength of the second noise blur", default=0.5)
+
+ def _srgb_to_linear(self, rgb: np.ndarray) -> np.ndarray:
+ a = 0.055
+ rgb = np.clip(rgb, 0.0, 1.0)
+ return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + a) / (1 + a)) ** 2.4)
+
+ def _linear_to_srgb(self, rgb_linear: np.ndarray) -> np.ndarray:
+ a = 0.055
+ rgb_linear = np.clip(rgb_linear, 0.0, 1.0)
+ return np.where(
+ rgb_linear <= 0.0031308,
+ rgb_linear * 12.92,
+ (1 + a) * (rgb_linear ** (1 / 2.4)) - a,
+ )
+
+ def _srgb_to_oklab(self, rgb: np.ndarray) -> np.ndarray:
+ rgb_linear = self._srgb_to_linear(rgb)
+
+ lms = np.tensordot(
+ rgb_linear,
+ np.array(
+ [
+ [0.4122214708, 0.5363325363, 0.0514459929],
+ [0.2119034982, 0.6806995451, 0.1073969566],
+ [0.0883024619, 0.2817188376, 0.6299787005],
+ ],
+ dtype=np.float64,
+ ).T,
+ axes=([2], [0]),
+ )
+
+ lms_cbrt = np.cbrt(lms)
+
+ lab = np.tensordot(
+ lms_cbrt,
+ np.array(
+ [
+ [0.2104542553, 0.7936177850, -0.0040720468],
+ [1.9779984951, -2.4285922050, 0.4505937099],
+ [0.0259040371, 0.7827717662, -0.8086757660],
+ ],
+ dtype=np.float64,
+ ).T,
+ axes=([2], [0]),
+ )
+
+ return lab.astype(np.float32)
+
+ def _oklab_to_srgb(self, lab: np.ndarray) -> np.ndarray:
+ lms_cbrt = np.tensordot(
+ lab,
+ np.array(
+ [
+ [1.0, 0.3963377774, 0.2158037573],
+ [1.0, -0.1055613458, -0.0638541728],
+ [1.0, -0.0894841775, -1.2914855480],
+ ],
+ dtype=np.float64,
+ ).T,
+ axes=([2], [0]),
+ )
+
+ lms = lms_cbrt**3
+
+ rgb_linear = np.tensordot(
+ lms,
+ np.array(
+ [
+ [4.0767416621, -3.3077115913, 0.2309699292],
+ [-1.2684380046, 2.6097574011, -0.3413193965],
+ [-0.0041960863, -0.7034186147, 1.7076147010],
+ ],
+ dtype=np.float64,
+ ).T,
+ axes=([2], [0]),
+ )
+
+ return self._linear_to_srgb(rgb_linear).astype(np.float32)
+
+ def _ab_sigma(self, amount: int) -> float:
+ # Map 0..800 -> OKLab a/b stddev
+ return 0.0008 * float(amount)
+
+ def _blur_unit_noise(self, unit_noise: np.ndarray, radius: float) -> np.ndarray:
+ """
+ Blur 2-channel unit noise using PIL in uint8 RGB (avoids Pillow's 'F' mode limitation).
+ unit_noise is expected to be roughly N(0,1).
+ """
+ if radius <= 0:
+ return unit_noise
+
+ # Pack (a_noise, b_noise, dummy) into RGB, blur once.
+ rgb = np.empty((unit_noise.shape[0], unit_noise.shape[1], 3), dtype=np.uint8)
+ rgb[..., 0] = np.clip(unit_noise[..., 0] * 127.5 + 127.5, 0.0, 255.0).astype(np.uint8)
+ rgb[..., 1] = np.clip(unit_noise[..., 1] * 127.5 + 127.5, 0.0, 255.0).astype(np.uint8)
+ rgb[..., 2] = 127 # constant channel
+
+ img = Image.fromarray(rgb, mode="RGB").filter(ImageFilter.GaussianBlur(radius=radius))
+ arr = np.asarray(img, dtype=np.float32)
+
+ out = np.empty_like(unit_noise, dtype=np.float32)
+ out[..., 0] = (arr[..., 0] - 127.5) / 127.5
+ out[..., 1] = (arr[..., 1] - 127.5) / 127.5
+ return out
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.get_pil(self.image.image_name)
+ mode = image.mode
+
+ alpha = None
+ if mode == "RGBA":
+ alpha = image.getchannel("A")
+ image = image.convert("RGB")
+ elif mode != "RGB":
+ image = image.convert("RGB")
+
+ rgb = np.asarray(image, dtype=np.float32) / 255.0
+ lab = self._srgb_to_oklab(rgb)
+
+ h, w = rgb.shape[0], rgb.shape[1]
+
+ rng = np.random.default_rng(seed=self.seed_1 if self.seed_1 is not None else get_random_seed())
+ n1_unit = rng.normal(0.0, 1.0, (h, w, 2)).astype(np.float32)
+ n1_unit = self._blur_unit_noise(n1_unit, self.blur_1)
+ n1 = n1_unit * self._ab_sigma(self.amount_1)
+
+ rng = np.random.default_rng(seed=self.seed_2 if self.seed_2 is not None else get_random_seed())
+ n2_unit = rng.normal(0.0, 1.0, (h, w, 2)).astype(np.float32)
+ n2_unit = self._blur_unit_noise(n2_unit, self.blur_2)
+ n2 = n2_unit * self._ab_sigma(self.amount_2)
+
+ lab_noisy = lab.copy()
+ lab_noisy[..., 1] = lab_noisy[..., 1] + n1[..., 0] + n2[..., 0]
+ lab_noisy[..., 2] = lab_noisy[..., 2] + n1[..., 1] + n2[..., 1]
+
+ rgb_out = (self._oklab_to_srgb(lab_noisy) * 255.0 + 0.5).astype(np.uint8)
+ out_img = Image.fromarray(rgb_out, mode="RGB")
+
+ if alpha is not None:
+ out_img = out_img.convert("RGBA")
+ out_img.putalpha(alpha)
+
+ image_dto = context.images.save(image=out_img)
+ return ImageOutput.build(image_dto)
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/lens_blur.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/lens_blur.py
new file mode 100644
index 0000000000..62ad10290d
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/lens_blur.py
@@ -0,0 +1,302 @@
+# Copyright (c) 2025 Jonathan S. Pollack (https://github.com/JPPhoto)
+
+from typing import Optional, Tuple
+
+import cv2
+import numpy as np
+from invokeai.invocation_api import (
+ BaseInvocation,
+ ImageField,
+ ImageOutput,
+ InputField,
+ InvocationContext,
+ WithBoard,
+ WithMetadata,
+ invocation,
+)
+from PIL import Image
+
+from .util import MyDepthMapPipeline # noqa: TID252
+
+
+@invocation("lens_blur", title="Lens Blur", tags=["image", "lens", "blur"], version="1.1.0")
+class LensBlurInvocation(BaseInvocation, WithBoard, WithMetadata):
+ """Adds lens blur to the input image, first converting the input image to RGB"""
+
+ image: ImageField = InputField(description="The image to streak")
+ depth_map: ImageField = InputField(description="The depth map to use")
+ aperture_image: Optional[ImageField] = InputField(description="The aperture image to use for convolution")
+ focal_distance: float = InputField(
+ description="The distance at which focus is sharp: 0.0 (near) - 1.0 (far)",
+ default=0.5,
+ ge=0.0,
+ le=1.0,
+ )
+ distance_range: float = InputField(
+ description="The depth of field range around the focal distance",
+ default=0.2,
+ ge=0.0,
+ le=1.0,
+ )
+ max_blur_radius: float = InputField(description="Maximum blur radius", default=5.0, gt=0.0)
+ max_blur_steps: int = InputField(description="Number of blur maps to use internally", default=32, gt=1)
+ anamorphic_factor: float = InputField(description="Anamorphic squeeze factor", default=1.33, ge=1.0)
+ highlight_threshold: float = InputField(
+ description="The luminance threshold at which highlight enhancement begins",
+ default=0.75,
+ ge=0.0,
+ le=1.0,
+ )
+ highlight_factor: float = InputField(
+ description="Minimum multiplier for highlights at the threshold",
+ default=1.0,
+ ge=1.0,
+ )
+ highlight_factor_high: float = InputField(
+ description="Maximum multiplier for highlights at full brightness",
+ default=2.0,
+ ge=1.0,
+ )
+ reduce_halos: bool = InputField(
+ description="Reduce halos around areas of sharp depth distance (SLOW)", default=True
+ )
+
+ def compute_blur_indices(self, depth_normalized: np.ndarray, num_blurred_images: int) -> np.ndarray:
+ # Use an asymmetric depth of field, using a 1/3 front, 2/3 back rule around the focal plane.
+ dof_front = 1 * self.distance_range / 3.0
+ dof_back = 2 * self.distance_range / 3.0
+
+ below = depth_normalized < self.focal_distance
+ above = ~below
+
+ distance_from_focus = np.zeros_like(depth_normalized)
+
+ # Front of focal plane
+ distance_from_focus[below] = np.clip((self.focal_distance - depth_normalized[below] - dof_front), 0.0, 1.0)
+
+ # Behind focal plane
+ distance_from_focus[above] = np.clip((depth_normalized[above] - self.focal_distance - dof_back), 0.0, 1.0)
+
+ # Normalize distance from focus
+ distance_from_focus = cv2.normalize(distance_from_focus, None, 0.0, 1.0, cv2.NORM_MINMAX)
+
+ # Scale to index range
+ indices = distance_from_focus * (num_blurred_images - 1)
+
+ return indices
+
+ def split_indices(self, indices: np.ndarray, num_blurred_images: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
+ lower_indices = np.floor(indices).astype(np.int32)
+ upper_indices = np.clip(lower_indices + 1, 0, num_blurred_images - 1)
+ alpha = (indices - lower_indices)[..., np.newaxis] # Shape: (H, W, 1)
+
+ return lower_indices, upper_indices, alpha
+
+ def apply_anamorphic_gaussian_blur(self, image: Image, sigma_y: float, anamorphic_squeeze: float) -> np.ndarray:
+ sigma_x = sigma_y / anamorphic_squeeze
+
+ image_numpy = image.astype(np.float32)
+
+ # Let OpenCV auto-calculate optimal kernel size from sigma
+ ksize = (0, 0)
+
+ # Apply the blur
+ blurred = cv2.GaussianBlur(image_numpy, ksize, sigmaX=sigma_x, sigmaY=sigma_y, borderType=cv2.BORDER_REFLECT)
+
+ return blurred
+
+ def fractional_resize(self, aperture_image_in: Image, kernel_width: float, kernel_height: float) -> Image:
+ desired_w, desired_h = int(round(kernel_width) // 2 * 2 + 1), int(round(kernel_height) // 2 * 2 + 1)
+ (aperture_w, aperture_h) = aperture_image_in.size
+
+ if desired_w == aperture_w and desired_h == aperture_h:
+ return aperture_image_in.copy()
+
+ resize_pct_w, resize_pct_h = desired_w / aperture_w, desired_h / aperture_h
+ temp_w, temp_h = int(aperture_w * 1.25), int(aperture_h * 1.25)
+ temp_scaled_w, temp_scaled_h = int(temp_w * resize_pct_w), int(temp_h * resize_pct_h)
+
+ aperture_image = Image.new("L", (temp_w, temp_h), 0)
+ offset = ((temp_w - aperture_w) // 2, (temp_h - aperture_h) // 2)
+ aperture_image.paste(aperture_image_in, offset)
+ aperture_image = aperture_image.resize((temp_scaled_w, temp_scaled_h), resample=Image.LANCZOS)
+
+ left = (temp_scaled_w - desired_w) // 2
+ top = (temp_scaled_h - desired_h) // 2
+ right = left + desired_w
+ bottom = top + desired_h
+ aperture_image = aperture_image.crop((left, top, right, bottom))
+ return aperture_image
+
+ def apply_aperture_image_blur(
+ self, image: Image, aperture_image: Image, kernel_height: float, anamorphic_squeeze: float
+ ) -> np.ndarray:
+ # A convenience function to help get the kernel sizing just right
+ def size_from_sigma(sigma: float) -> Tuple[int, float]:
+ rounded_size = 2 * int(np.ceil(3 * sigma)) + 1
+ actual_size = 6 * sigma + 1
+ return rounded_size, actual_size
+
+ image_numpy = image.astype(np.float32)
+
+ # Resize the original proportionally
+ kernel_width = kernel_height / anamorphic_squeeze
+ resized_kernel_img = self.fractional_resize(aperture_image, kernel_width, kernel_height)
+
+ # Extract, flip, and normalize the convolution kernel
+ resized_kernel_img = resized_kernel_img.transpose(Image.FLIP_TOP_BOTTOM)
+ resized_kernel_img = resized_kernel_img.transpose(Image.FLIP_LEFT_RIGHT)
+ kernel = np.array(resized_kernel_img, dtype=np.float32)
+ kernel /= kernel.sum()
+
+ # Apply convolution channel-wise
+ blurred = np.stack(
+ [
+ cv2.filter2D(image_numpy[..., c], -1, kernel, borderType=cv2.BORDER_REFLECT)
+ for c in range(image_numpy.shape[2])
+ ],
+ axis=2,
+ )
+
+ return blurred
+
+ def apply_blur_based_on_depth(
+ self, blurred_images: list[np.ndarray], depth_map: np.ndarray, indices: np.ndarray
+ ) -> np.ndarray:
+ num_blurred_images = len(blurred_images)
+ lower_indices, upper_indices, alpha = self.split_indices(indices, num_blurred_images)
+
+ output = np.zeros_like(blurred_images[0], dtype=np.float32)
+
+ for i in range(num_blurred_images):
+ mask_lower = lower_indices == i
+ mask_upper = upper_indices == i
+
+ if blurred_images[0].ndim == 3:
+ mask_lower = mask_lower[..., np.newaxis]
+ mask_upper = mask_upper[..., np.newaxis]
+
+ output += blurred_images[i] * mask_lower * (1 - alpha) + blurred_images[i] * mask_upper * alpha
+
+ return output
+
+ def enhance_highlights(self, image: np.ndarray) -> np.ndarray:
+ image = image.astype(np.float32) / 255.0
+
+ # Compute per-pixel luminance (ITU-R BT.709)
+ luminance = 0.2126 * image[..., 0] + 0.7152 * image[..., 1] + 0.0722 * image[..., 2]
+
+ # Calculate per-pixel enhancement factor
+ mask = luminance >= self.highlight_threshold
+ t = np.clip((luminance - self.highlight_threshold) / (1.0 - self.highlight_threshold), 0.0, 1.0)
+ factor = self.highlight_factor * (1.0 - t) + self.highlight_factor_high * t
+
+ # Expand factor to 3 channels
+ factor_expanded = np.where(mask[..., None], factor[..., None], 1.0)
+
+ # Apply enhancement
+ enhanced = image * factor_expanded
+ enhanced = enhanced * 255.0
+
+ return enhanced
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.get_pil(self.image.image_name)
+
+ image_mode = image.mode
+ image = image.convert("RGB")
+
+ if self.depth_map:
+ depth_map = context.images.get_pil(self.depth_map.image_name)
+
+ # In case we got an RGB depth map
+ depth_map = depth_map.convert("L")
+
+ depth_map_numpy = np.array(depth_map)
+ else:
+ # Do our own depth estimation
+ model_url = "depth-anything/Depth-Anything-V2-Small-hf"
+ loaded_model = context.models.load_remote_model(model_url, MyDepthMapPipeline.load_model)
+
+ with loaded_model as depth_anything_detector:
+ depth_map = depth_anything_detector.generate_depth(image)
+
+ """
+ # Interpolate to original size
+ post_processed_output = self._image_processor.post_process_depth_estimation(
+ outputs,
+ target_sizes=[(image.height, image.width)],
+ )
+
+ # Visualize the prediction
+ predicted_depth = post_processed_output[0]["predicted_depth"]
+ depth_map = predicted_depth * 255 / predicted_depth.max()
+ depth_map_numpy = depth_map.detach().cpu().numpy()
+ """
+
+ # Slightly blur
+ depth_map = cv2.GaussianBlur(depth_map_numpy, (0, 0), 3)
+
+ # Normalize and invert depth map
+ depth_normalized = 1 - cv2.normalize(depth_map_numpy.astype(np.float32), None, 0.0, 1.0, cv2.NORM_MINMAX)
+
+ # Get blur indices so we can use for blurring and depth compositing
+ indices = self.compute_blur_indices(depth_normalized, self.max_blur_steps)
+
+ img_blurred = [None] * self.max_blur_steps
+
+ image_numpy = np.array(image)
+ image_numpy = self.enhance_highlights(image_numpy)
+ img_blurred[0] = image_numpy
+
+ if self.reduce_halos:
+ # Get a mask to remove closer things and use cv2 infill
+ lower_indices, _, _ = self.split_indices(indices, self.max_blur_steps)
+
+ aperture_image = context.images.get_pil(self.aperture_image.image_name)
+ (aperture_w, aperture_h) = aperture_image.size
+ if aperture_w != aperture_h or aperture_w < 512:
+ raise ValueError("Provided aperture image is not a square and must be at least 512x512")
+ aperture_image = aperture_image.convert("L")
+
+ for blur in range(1, self.max_blur_steps):
+ # Copy the image to preserve the original
+ image_to_blur = np.array(image)
+
+ if self.reduce_halos:
+ # Mask where indices are < blur
+ mask = (indices < (blur - self.max_blur_steps // 10)).astype(np.uint8)
+ mask = mask * 255
+
+ # Inpaint masked regions
+ image_to_blur = cv2.inpaint(image_to_blur, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
+
+ # Add highlights
+ image_to_blur = self.enhance_highlights(image_to_blur)
+
+ def bokeh_size(d, MAX):
+ return (d / MAX) ** 0.10
+
+ if self.aperture_image is None:
+ # Use Gaussian blur
+ img_blurred[blur] = self.apply_anamorphic_gaussian_blur(
+ image_to_blur,
+ self.max_blur_radius * bokeh_size(blur, (self.max_blur_steps - 1)),
+ self.anamorphic_factor,
+ )
+ else:
+ # Use aperture blur
+ img_blurred[blur] = self.apply_aperture_image_blur(
+ image_to_blur,
+ aperture_image,
+ self.max_blur_radius * bokeh_size(blur, (self.max_blur_steps - 1)),
+ self.anamorphic_factor,
+ )
+
+ img_blurred = self.apply_blur_based_on_depth(img_blurred, depth_map_numpy, indices)
+ img_blurred = np.clip(img_blurred, 0, 255).astype(np.uint8)
+ lens_blurred_image = Image.fromarray(img_blurred).convert(image_mode)
+
+ image_dto = context.images.save(image=lens_blurred_image)
+
+ return ImageOutput.build(image_dto)
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/lens_vignette.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/lens_vignette.py
new file mode 100644
index 0000000000..b7ee53e92d
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/lens_vignette.py
@@ -0,0 +1,131 @@
+# Copyright (c) 2025 Jonathan S. Pollack (https://github.com/JPPhoto)
+
+import numpy as np
+from invokeai.invocation_api import (
+ BaseInvocation,
+ ImageField,
+ ImageOutput,
+ InputField,
+ InvocationContext,
+ WithBoard,
+ WithMetadata,
+ invocation,
+)
+from PIL import Image
+
+from .util import oklch_to_rgb, rgb_to_oklch # noqa: TID252
+
+
+@invocation(
+ "lens_vignette",
+ title="Lens Vignette",
+ tags=["image", "postprocessing", "vignette"],
+ category="image",
+ version="1.2.0",
+)
+class LensVignetteInvocation(BaseInvocation, WithBoard, WithMetadata):
+ """Apply realistic lens vignetting to an image with configurable parameters."""
+
+ image: ImageField = InputField(description="The image to apply vignetting to")
+ intensity: float = InputField(default=0.5, ge=0.0, le=4.0, description="Intensity of the vignette effect (0-4)")
+ aperture_factor: float = InputField(
+ default=0.5, ge=0.2, le=1.5, description="Aperture falloff factor (>1.2 = strong, <0.5 = weak)"
+ )
+ center_x: float = InputField(default=0.5, ge=0.0, le=1.0, description="X coordinate of vignette center (0-1)")
+ center_y: float = InputField(default=0.5, ge=0.0, le=1.0, description="Y coordinate of vignette center (0-1)")
+ preserve_highlights: bool = InputField(default=True, description="Preserve highlights")
+
+ def do_highlight_preservation(
+ self, img_oklch: np.ndarray, img_vignetted: np.ndarray, highlights_vignetted: np.ndarray
+ ) -> np.ndarray:
+ L = img_oklch[..., 0]
+ highlight = np.clip((L - 0.7) / 0.4, 0.0, 1.0) ** 1.5
+
+ result_L = highlight * highlights_vignetted[..., 0] + (1.0 - highlight) * img_vignetted[..., 0]
+
+ # Replace only the L channel
+ result = img_vignetted.copy()
+ result[..., 0] = np.clip(result_L, 0.0, 1.0)
+ return result
+
+ def apply_vignette(self, image: Image.Image) -> Image.Image:
+ """Apply a cosine-fourth power vignette effect with optional off-center falloff."""
+
+ # Load and normalize image
+ img = np.array(image).astype(np.float32) / 255.0
+ if img.ndim == 2:
+ img = img[..., None]
+
+ ch = img.shape[2]
+ if ch == 1:
+ rgb, alpha = img, None
+ elif ch == 2:
+ rgb, alpha = img[..., :1], img[..., 1:2]
+ elif ch == 3:
+ rgb, alpha = img, None
+ elif ch == 4:
+ rgb, alpha = img[..., :3], img[..., 3:4]
+ else:
+ rgb, alpha = img[..., :3], img[..., 3:] if ch > 3 else None
+
+ img_oklch = rgb_to_oklch(rgb)
+ img_oklch[..., 2] = np.where(img_oklch[..., 1] > 1e-8, img_oklch[..., 2], 0.0)
+
+ height, width = img.shape[:2]
+ y, x = np.mgrid[0:height, 0:width]
+ cx = self.center_x * width
+ cy = self.center_y * height
+
+ dx = x - cx
+ dy = y - cy
+ distance = np.sqrt(dx**2 + dy**2)
+ max_dist = np.sqrt(
+ max(
+ cx**2 + cy**2,
+ (width - cx) ** 2 + cy**2,
+ cx**2 + (height - cy) ** 2,
+ (width - cx) ** 2 + (height - cy) ** 2,
+ )
+ )
+ r = distance / max_dist
+
+ # Cosine-fourth law
+ vignette = np.cos(np.clip(r * self.aperture_factor, 0.0, 1.0) * (np.pi / 2)) ** 4
+ vignette_mask = 1.0 - self.intensity * (1.0 - vignette)
+ vignette_mask = vignette_mask[..., None] # expand for broadcast
+ vignette_mask = np.clip(vignette_mask, 0.0, 1.0)
+
+ img_vignetted = img_oklch.copy()
+ img_vignetted[..., 0] *= vignette_mask[..., 0] # apply only to L channel
+
+ if self.preserve_highlights:
+ highlight_mask = 1.0 - (self.intensity * 0.5) * (1.0 - vignette)
+ highlight_mask = highlight_mask[..., None]
+ highlight_mask = np.clip(highlight_mask, 0.0, 1.0)
+
+ highlights_vignetted = img_oklch.copy()
+ highlights_vignetted[..., 0] *= highlight_mask[..., 0]
+
+ img_oklch = self.do_highlight_preservation(img_oklch, img_vignetted, highlights_vignetted)
+ else:
+ img_oklch = img_vignetted
+
+ rgb_srgb = oklch_to_rgb(img_oklch)
+
+ if alpha is not None:
+ out = np.concatenate([rgb_srgb, alpha], axis=2)
+ else:
+ out = rgb_srgb
+
+ result = (out * 255.0).clip(0, 255).astype(np.uint8)
+ if result.ndim == 3 and result.shape[2] == 1:
+ result = result[:, :, 0]
+ return Image.fromarray(result)
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ pil_image = context.images.get_pil(self.image.image_name)
+ result_image = self.apply_vignette(pil_image)
+
+ image_dto = context.images.save(image=result_image)
+
+ return ImageOutput.build(image_dto)
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/spherical_distortion.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/spherical_distortion.py
new file mode 100644
index 0000000000..0172019fc6
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/spherical_distortion.py
@@ -0,0 +1,192 @@
+# Copyright (c) 2025 Jonathan S. Pollack (https://github.com/JPPhoto)
+
+import cv2
+import numpy as np
+from invokeai.invocation_api import (
+ BaseInvocation,
+ ImageField,
+ ImageOutput,
+ InputField,
+ InvocationContext,
+ WithBoard,
+ WithMetadata,
+ invocation,
+)
+from PIL import Image
+
+
+@invocation("spherical_distortion", title="Spherical Distortion", tags=["image", "anamorphic"], version="1.1.0")
+class SphericalDistortionInvocation(BaseInvocation, WithBoard, WithMetadata):
+ """Applies spherical distortion to an image and fills the frame with the resulting image"""
+
+ image: ImageField = InputField(description="The image to distort")
+ k1: float = InputField(description="k1", default=0.3)
+ k2: float = InputField(description="k2", default=0.1)
+ p1: float = InputField(description="p1", default=0.0)
+ p2: float = InputField(description="p2", default=0.0)
+
+ def calculate_optimal_zoom(self, width, height, k1, k2, p1=0.0, p2=0.0):
+ """
+ Calculate the optimal zoom factor needed to fill the frame after distortion.
+
+ Args:
+ k1, k2: Radial distortion coefficients
+ width, height: Dimensions of the image
+ p1, p2: Tangential distortion coefficients
+
+ Returns:
+ Optimal zoom factor
+ """
+ # Normalize corner coordinates to [-1, 1] range
+ x_corners = [1.0, -1.0, 1.0, -1.0]
+ y_corners = [1.0, 1.0, -1.0, -1.0]
+
+ # Calculate maximum distortion at corners
+ max_distortion = 1.0
+ for x, y in zip(x_corners, y_corners):
+ r_squared = (x * width / 2) ** 2 + (y * height / 2) ** 2
+ r_quad = r_squared**2
+ distortion_factor = 1.0 + k1 * r_squared + k2 * r_quad
+ tangential_offset = 2 * p1 * x * y + p2 * (r_squared + 2 * x**2)
+
+ # Combined effect
+ distorted_x = x * distortion_factor + tangential_offset
+ distorted_y = y * distortion_factor + tangential_offset
+ max_distortion = max(max_distortion, abs(distorted_x), abs(distorted_y))
+
+ # Zoom to compensate for distortion
+ optimal_zoom = 1.05 * max_distortion if max_distortion > 1.0 else 0.95 / max_distortion
+ return optimal_zoom
+
+ def apply_advanced_spherical_distortion_cv2(
+ self, pil_image, k1=0.3, k2=0.1, p1=0.0, p2=0.0, auto_zoom=True, zoom=1.0
+ ):
+ """
+ Apply advanced spherical distortion with multiple distortion coefficients using OpenCV.
+ Includes both radial (k1, k2) and tangential (p1, p2) distortion parameters.
+
+ Args:
+ pil_image: PIL Image object
+ k1: Primary radial distortion coefficient
+ k2: Secondary radial distortion coefficient
+ p1, p2: Tangential distortion coefficients (default 0)
+ auto_zoom: Whether to automatically calculate zoom to fill frame (overrides zoom parameter)
+ zoom: Manual zoom factor (only used if auto_zoom is False)
+
+ Returns:
+ PIL Image with advanced lens distortion applied
+
+ Typical Panavision Anamorphic Lens Parameter Values:
+ Classic Panavision (C Series Anamorphic):
+ k1 = 0.25 to 0.35, k2 = 0.15 to 0.25, p1 = 0.01, p2 = 0.01
+
+ Panavision Primo Anamorphic:
+ k1 = 0.15 to 0.25, k2 = 0.05 to 0.15, p1 = 0.005, p2 = 0.005
+
+ Panavision E Series Anamorphic:
+ k1 = 0.30 to 0.40, k2 = 0.20 to 0.30, p1 = 0.01, p2 = 0.01
+
+ Panavision G Series Anamorphic (vintage look):
+ k1 = 0.40 to 0.50, k2 = 0.25 to 0.35, p1 = 0.02, p2 = 0.02
+
+ Panavision T Series Anamorphic:
+ k1 = 0.20 to 0.30, k2 = 0.10 to 0.20, p1 = 0.005, p2 = 0.005
+ """
+ # Get the width and height
+ width, height = pil_image.size
+
+ # Convert PIL image to OpenCV format
+ cv_image = np.array(pil_image)
+
+ # Handle RGB vs RGBA
+ if len(cv_image.shape) == 3 and cv_image.shape[2] == 3:
+ cv_image = cv2.cvtColor(cv_image, cv2.COLOR_RGB2BGR)
+ elif len(cv_image.shape) == 3 and cv_image.shape[2] == 4:
+ cv_image = cv2.cvtColor(cv_image, cv2.COLOR_RGBA2BGRA)
+
+ # Calculate optimal zoom if requested
+ if auto_zoom:
+ zoom = self.calculate_optimal_zoom(width, height, k1, k2, p1, p2)
+
+ # Create camera matrix (focal length and principal point)
+ focal_length = width
+ camera_matrix = np.array(
+ [[focal_length, 0, width / 2], [0, focal_length, height / 2], [0, 0, 1]], dtype=np.float64
+ )
+
+ # Define distortion coefficients [k1, k2, p1, p2, k3]
+ # k3 is set to 0 for simplicity
+ dist_coeffs = np.array([k1, k2, p1, p2, 0], dtype=np.float64)
+
+ # Generate new camera matrix with adjusted zoom
+ alpha = 1.0 / zoom # Inverse of zoom for OpenCV's convention
+ new_camera_matrix = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coeffs, (width, height), alpha)[0]
+
+ # Apply distortion using undistort (OpenCV uses inverted distortion model)
+ distorted_image = cv2.undistort(cv_image, camera_matrix, dist_coeffs, None, new_camera_matrix)
+
+ # Convert back to PIL
+ if len(cv_image.shape) == 3 and cv_image.shape[2] == 3:
+ distorted_image = cv2.cvtColor(distorted_image, cv2.COLOR_BGR2RGB)
+ result_pil = Image.fromarray(distorted_image)
+ elif len(cv_image.shape) == 3 and cv_image.shape[2] == 4:
+ distorted_image = cv2.cvtColor(distorted_image, cv2.COLOR_BGRA2RGBA)
+ result_pil = Image.fromarray(distorted_image)
+ else:
+ result_pil = Image.fromarray(distorted_image)
+
+ return result_pil
+
+ def crop_to_remove_black_borders(self, pil_image, threshold=0):
+ """
+ Automatically detect and crop black/empty borders from an image.
+ Useful as a post-processing step after distortion.
+
+ Args:
+ pil_image: PIL image
+ threshold: Value to consider as "black" (default 0)
+
+ Returns:
+ Cropped PIL image
+ """
+ # Convert to numpy array for processing
+ np_image = np.array(pil_image)
+
+ # Handle different image modes
+ if len(np_image.shape) == 3:
+ # For RGB/RGBA images, take sum across color channels
+ # If any channel has value, it's not black
+ mask = np_image.sum(axis=2) > threshold
+ else:
+ # For grayscale
+ mask = np_image > threshold
+
+ # Find the bounding box of non-black pixels
+ coords = np.argwhere(mask)
+
+ if len(coords) == 0:
+ # No non-black pixels found
+ return pil_image
+
+ y_min, x_min = coords.min(axis=0)
+ y_max, x_max = coords.max(axis=0)
+
+ # Crop the image to those coordinates
+ cropped = pil_image.crop((x_min, y_min, x_max + 1, y_max + 1))
+
+ return cropped
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.get_pil(self.image.image_name)
+
+ distorted_image = self.apply_advanced_spherical_distortion_cv2(
+ image,
+ self.k1,
+ self.k2,
+ self.p1,
+ self.p2,
+ )
+
+ image_dto = context.images.save(image=distorted_image)
+
+ return ImageOutput.build(image_dto)
diff --git a/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/util.py b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/util.py
new file mode 100644
index 0000000000..34404c7dc6
--- /dev/null
+++ b/tests/app/invocations/third_party_cinematic_effects/cinematic_effects/util.py
@@ -0,0 +1,73 @@
+import pathlib
+from typing import Optional
+
+import numpy as np
+import torch
+from invokeai.backend.raw_model import RawModel
+from invokeai.invocation_api import oklch_from_srgb, srgb_from_oklch
+from PIL import Image
+from transformers import AutoImageProcessor, AutoModelForDepthEstimation
+
+
+def rgb_to_oklch(rgb: np.ndarray) -> np.ndarray:
+ rgb_tensor = torch.from_numpy(np.clip(rgb, 0.0, 1.0)).permute(2, 0, 1).to(dtype=torch.float64)
+ return oklch_from_srgb(rgb_tensor).permute(1, 2, 0).numpy()
+
+
+def oklch_to_rgb(oklch: np.ndarray) -> np.ndarray:
+ oklch_tensor = torch.from_numpy(oklch).permute(2, 0, 1).to(dtype=torch.float64)
+ return srgb_from_oklch(oklch_tensor).permute(1, 2, 0).numpy()
+
+
+class MyDepthMapPipeline(RawModel):
+ """Custom wrapper for the Depth Estimation pipeline from transformers adding compatibility
+ for Invoke's Model Management System plus returning fp depth"""
+
+ def __init__(self, image_processor: AutoImageProcessor, depth_model: AutoModelForDepthEstimation) -> None:
+ print("__init__")
+ self._image_processor = image_processor
+ self._depth_model = depth_model
+
+ def generate_depth(self, image: Image.Image) -> Image.Image:
+ print("GD")
+ # Prepare image for the model
+ inputs = self._image_processor(images=image, return_tensors="pt")
+
+ with torch.no_grad():
+ outputs = self._depth_model(**inputs)
+
+ # Interpolate to original size
+ post_processed_output = self._image_processor.post_process_depth_estimation(
+ outputs,
+ target_sizes=[(image.height, image.width)],
+ )
+
+ # Visualize the prediction
+ predicted_depth = post_processed_output[0]["predicted_depth"]
+ depth_map = predicted_depth * 255 / predicted_depth.max()
+ depth_map = depth_map.detach().cpu().numpy()
+ print("DM")
+
+ return depth_map
+
+ def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None):
+ if device is not None and device.type not in {"cpu", "cuda"}:
+ device = None
+ self._image_processor.model.to(device=device, dtype=dtype)
+ self._image_processor.device = self._pipeline.model.device
+ self._depth_model.model.to(device=device, dtype=dtype)
+ self._depth_model.device = self._pipeline.model.device
+
+ def calc_size(self) -> int:
+ from invokeai.backend.model_manager.load.model_util import calc_module_size
+
+ return calc_module_size(self._image_processor.model) + calc_module_size(self._depth_model)
+
+ @classmethod
+ def load_model(cls, model_path: pathlib.Path):
+ """Load the model from the given path and return a MyDepthMapPipeline instance."""
+
+ print("__load_model__")
+ image_processor = AutoImageProcessor.from_pretrained(str(model_path))
+ depth_model = AutoModelForDepthEstimation.from_pretrained(str(model_path))
+ return MyDepthMapPipeline(image_processor, depth_model)
diff --git a/tests/app/services/image_files/test_image_files_disk.py b/tests/app/services/image_files/test_image_files_disk.py
index 69efdd079b..64af6ea83b 100644
--- a/tests/app/services/image_files/test_image_files_disk.py
+++ b/tests/app/services/image_files/test_image_files_disk.py
@@ -93,6 +93,50 @@ def disk_storage(tmp_path: Path) -> DiskImageFileStorage:
return storage
+def test_saved_image_is_cached_independently_of_the_callers_object(disk_storage: DiskImageFileStorage):
+ """A node that keeps drawing on its canvas after saving must not rewrite what the next read returns."""
+ canvas = Image.new("RGB", (8, 8), (10, 20, 30))
+ canvas.info = {"caller": "kept"}
+ on_disk = canvas.tobytes()
+
+ disk_storage.save(canvas, "frame.png", metadata="{}")
+ canvas.paste((255, 255, 255), (0, 0, 8, 8))
+
+ assert disk_storage.get("frame.png").tobytes() == on_disk
+ assert canvas.info == {"caller": "kept"}
+
+
+def test_saving_over_an_existing_name_returns_the_new_image(disk_storage: DiskImageFileStorage):
+ disk_storage.save(Image.new("RGB", (8, 8), (10, 20, 30)), "frame.png")
+ assert disk_storage.get("frame.png").getpixel((0, 0)) == (10, 20, 30)
+
+ disk_storage.save(Image.new("RGB", (8, 8), (200, 100, 50)), "frame.png")
+
+ assert disk_storage.get("frame.png").getpixel((0, 0)) == (200, 100, 50)
+
+
+def test_a_read_that_began_before_an_overwrite_cannot_cache_the_old_file_afterwards(
+ disk_storage: DiskImageFileStorage,
+):
+ """Reads of other images push the overwritten one out of the cache (eviction does not bump the generation);
+ only the overwrite's own bump keeps the late fill of the old pixels out."""
+ old = Image.new("RGB", (8, 8), (10, 20, 30))
+ disk_storage.save(old, "frame.png")
+ path = disk_storage.get_path("frame.png")
+ _, generation = disk_storage._DiskImageFileStorage__get_cache(path) # type: ignore[attr-defined]
+
+ disk_storage.save(Image.new("RGB", (8, 8), (200, 100, 50)), "frame.png")
+ for index in range(10):
+ other = f"other-{index}.png"
+ Image.new("RGB", (8, 8)).save(disk_storage.get_path(other), format="PNG")
+ disk_storage.get(other)
+ cache = disk_storage._DiskImageFileStorage__cache # type: ignore[attr-defined]
+ assert path not in cache
+ disk_storage._DiskImageFileStorage__set_cache(path, old, generation) # type: ignore[attr-defined]
+
+ assert disk_storage.get("frame.png").getpixel((0, 0)) == (200, 100, 50)
+
+
def test_directory_traversal_protection(tmp_path: Path, image_names: list[str]):
"""Test that the image file storage prevents directory traversal attacks.
diff --git a/tests/app/services/shared/test_invocation_context_images.py b/tests/app/services/shared/test_invocation_context_images.py
index 6bd0189eb4..c8a511eccf 100644
--- a/tests/app/services/shared/test_invocation_context_images.py
+++ b/tests/app/services/shared/test_invocation_context_images.py
@@ -103,6 +103,22 @@ def test_image_reads_reject_foreign_private_image(method_name: str, service_meth
getattr(services.images, service_method).assert_not_called()
+def test_get_pil_keeps_the_cached_image_intact_when_the_conversion_fails() -> None:
+ """LAB has no conversion to L: the original mode is returned, as a copy rather than the service's object."""
+ images, services = _make_interface(allowed=True)
+ cached = Image.new("LAB", (4, 4), (50, 128, 128))
+ services.images.get_pil_image.return_value = cached
+ expected = cached.tobytes()
+
+ result = images.get_pil("lab-image", "L")
+
+ assert result.mode == "LAB"
+ assert result is not cached
+ result.paste((255, 0, 0), (0, 0, 4, 4))
+ assert cached.tobytes() == expected
+ services.logger.warning.assert_called_once()
+
+
def test_image_dto_allows_foreign_shared_image() -> None:
images, services = _make_interface(allowed=True)
services.image_records.get_user_id.return_value = "owner"