Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add raster image mobjects

Sina Atalay1424f6843674
diff --git a/src/manimgx/mobjects/images.py b/src/manimgx/mobjects/images.py
new file mode 100644
index 00000000..3f648740
--- /dev/null
+++ b/src/manimgx/mobjects/images.py
@@ -0,0 +1,326 @@
+"Pictures on meshes: decoded pixels and live camera views."
+
+from pathlib import Path
+from typing import TYPE_CHECKING, Self, Unpack
+
+import numpy as np
+
+from manimgx.config import config
+from manimgx.constants import DOWN, LEFT, RIGHT, UP, Resampling
+from manimgx.drawing.paint import (
+ WHITE,
+ YELLOW_C,
+ Fill,
+ Look,
+ ManimColor,
+ ParsableManimColor,
+ Style,
+)
+from manimgx.mobject import MeshMobject
+
+__all__ = ["ImageMobject", "ImageMobjectFromCamera"]
+
+if TYPE_CHECKING:
+ from manimgx.mobjects.annotations import FrameOptions
+ from manimgx.scene import Camera
+
+
+class ImageMobject(MeshMobject):
+ """A picture: an image file or an array of pixels, on a rectangle as tall as its
+ pixels make it.
+
+ An image `scale_to_resolution` pixels tall (1080 unless given) is as tall as the
+ frame, 8 scene units, and any other in proportion. Shown larger than its pixels, the
+ picture is reconstructed from them by `resampling_algorithm`: by default a smooth
+ cubic through every pixel; linear blends neighboring pixels; nearest shows each
+ pixel as a square of its color. Shown smaller, it is sampled, not averaged. The
+ mobject's opacity multiplies its pixels' own.
+
+ Args:
+ filename_or_array: The picture: an image file's path, the file's contents
+ (bytes), or an array of pixel values from 0 to 255: (h, w) gray, (h, w, 3)
+ RGB or (h, w, 4) RGBA.
+ scale_to_resolution: How many pixels tall an image as tall as the frame is; 0
+ for an image 3 units tall, whatever its size.
+ invert: Whether its colors are inverted (not its transparency).
+ image_mode: The mode, as the Pillow library names them, a file is read in:
+ "RGBA", or "L" for gray.
+ resampling_algorithm: How the picture is reconstructed from its pixels, by the
+ Pillow library's number: 0, nearest; 2, linear; 3, cubic (Keys' cubic
+ convolution, Pillow's bicubic);
+ [RESAMPLING_ALGORITHMS][manimgx.RESAMPLING_ALGORITHMS] gives them by name.
+ stroke_width: The width of a border around the picture, in hundredths of a
+ scene unit; 0 for none.
+ stroke_color: The border's color.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class ImageMobjectExample(m.Scene):
+ def construct(self) -> None:
+ ramp = np.linspace(0, 255, 256)
+ pixels = np.zeros((256, 256, 3), dtype=np.uint8)
+ pixels[..., 0] = ramp # red grows to the right
+ pixels[..., 2] = ramp[:, np.newaxis] # blue grows downward
+ image = m.ImageMobject(pixels, scale_to_resolution=400)
+ self.play(m.FadeIn(image))
+ ```
+
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class ImageMobjectResamplingExample(m.Scene):
+ def construct(self) -> None:
+ pixels = np.full((3, 3), 60, dtype=np.uint8)
+ pixels[1, 1] = 255 # one white pixel, amid gray ones
+ images = m.Group()
+ for name in ("nearest", "linear", "cubic"):
+ image = m.ImageMobject(
+ pixels,
+ scale_to_resolution=6,
+ resampling_algorithm=m.RESAMPLING_ALGORITHMS[name],
+ )
+ images.add(m.Group(image, m.Text(name).next_to(image, m.DOWN)))
+ self.add(images.arrange(buff=0.5))
+ ```
+ """
+
+ # a textured quad, CE's four corners (UL, UR, DL, DR) its vertices; the opacity lives
+ # in the paint, a multiplier
+ def __init__(
+ self,
+ filename_or_array: str | Path | bytes | np.ndarray,
+ scale_to_resolution: int = 1080,
+ invert: bool = False,
+ image_mode: str = "RGBA",
+ resampling_algorithm: Resampling = 3,
+ stroke_width: float = 0, # a border's (the picture is the texture)
+ stroke_color: ParsableManimColor = WHITE,
+ **kwargs: Unpack[Look],
+ ) -> None:
+ import io
+
+ from PIL import Image
+
+ if isinstance(filename_or_array, (str, Path, bytes)):
+ source = (
+ io.BytesIO(filename_or_array)
+ if isinstance(filename_or_array, bytes)
+ else filename_or_array
+ )
+ pixels = np.array(Image.open(source).convert(image_mode))
+ else:
+ pixels = np.array(filename_or_array)
+ pixels = _to_rgba(pixels)
+ if invert:
+ pixels[:, :, :3] = 255 - pixels[:, :, :3]
+ pixels.flags.writeable = False
+ self.scale_to_resolution = scale_to_resolution
+ self.resampling_algorithm = resampling_algorithm
+ super().__init__(
+ np.array([UP + LEFT, UP + RIGHT, DOWN + LEFT, DOWN + RIGHT], dtype=float),
+ np.array([[0, 1, 2], [1, 3, 2]]),
+ uvs=np.array([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=float),
+ texture=pixels,
+ **kwargs,
+ )
+ if (
+ stroke_width > 0
+ ): # a border is just a rectangle child that follows every transform
+ from manimgx.mobjects.shapes import Polygon
+
+ self.add(
+ Polygon(
+ *self.points[[0, 1, 3, 2]],
+ stroke_width=stroke_width,
+ stroke_color=stroke_color,
+ )
+ )
+
+ @property
+ def pixel_array(self) -> np.ndarray:
+ """The current picture's (h, w, 4) RGBA pixels, from 0 to 255.
+
+ Pictures decoded or tinted by this image are read-only. Becoming another
+ textured mesh adopts its texture, including whether it is writable.
+ """
+ texture = self.paint.texture
+ assert isinstance(texture, np.ndarray)
+ return texture
+
+ def generate_points(self) -> Self:
+ super().generate_points()
+ self.center()
+ texture = self._texture
+ assert isinstance(texture, np.ndarray)
+ h, w = texture.shape[:2]
+ height = (
+ h / self.scale_to_resolution * config.frame_height
+ if self.scale_to_resolution
+ else 3
+ )
+ return self.stretch_to_fit_height(height).stretch_to_fit_width(height * w / h)
+
+ def set_color( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE's: an image's tint, then its alpha
+ self,
+ color: ParsableManimColor = YELLOW_C,
+ alpha: float | None = None,
+ family: bool = True,
+ ) -> Self:
+ """Paint every pixel `color`, keeping its opacity: the picture becomes a
+ silhouette in that color.
+
+ Args:
+ alpha: Every pixel's opacity too, from 0 to 1; None keeps each one's.
+ family: Accepted for Manim compatibility; ignored: the picture alone is
+ painted.
+ """
+ pixels = self.pixel_array.copy()
+ pixels[:, :, :3] = (ManimColor(color).to_rgb() * 255).astype(np.uint8)
+ if alpha is not None:
+ pixels[:, :, 3] = int(255 * alpha)
+ pixels.flags.writeable = False
+ self.paint = self.paint.but(texture=pixels)
+ return self
+
+ def set_opacity(
+ self, opacity: float = 1.0, family: bool = True, *, alpha: float | None = None
+ ) -> Self:
+ """Set the picture's opacity, which multiplies its pixels' own.
+
+ Args:
+ opacity: The opacity, from 0 to 1.
+ family: Whether its whole family is set (a border too), or the picture
+ alone.
+ alpha: The opacity, by the name Manim's images give it; given, it wins over
+ `opacity`.
+ """
+ return super().set_opacity(opacity if alpha is None else alpha, family)
+
+ def set_resampling_algorithm(self, resampling_algorithm: Resampling) -> Self:
+ """Set how the picture is reconstructed from its pixels where it is shown larger
+ than they are.
+
+ Args:
+ resampling_algorithm: The filter, by the Pillow library's number: 0, nearest
+ (each pixel a square of its color); 2, linear; 3, cubic (smooth, and
+ through every pixel);
+ [RESAMPLING_ALGORITHMS][manimgx.RESAMPLING_ALGORITHMS] gives them by
+ name.
+ """
+ self.resampling_algorithm = resampling_algorithm
+ return self
+
+ def get_style(self) -> Fill:
+ """The picture's style, as fill keywords: its color and its opacity.
+
+ Returns:
+ A dict of `fill_color` and `fill_opacity`.
+ """
+ return Fill(fill_color=self.get_color(), fill_opacity=self.get_fill_opacity())
+
+
+def _to_rgba(pixels: np.ndarray) -> np.ndarray:
+ if pixels.ndim == 2:
+ pixels = np.stack([pixels] * 3, axis=-1)
+ if pixels.shape[2] == 3:
+ pixels = np.concatenate(
+ [pixels, np.full((*pixels.shape[:2], 1), 255, dtype=pixels.dtype)], axis=2
+ )
+ return pixels.astype(np.uint8)
+
+
+class ImageCameraOptions(Style, total=False):
+ """A camera picture's keywords, those of an
+ [ImageMobjectFromCamera][manimgx.ImageMobjectFromCamera], for the scenes that pass
+ them on: a [ZoomedScene][manimgx.ZoomedScene]'s display.
+
+ Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].
+ """
+
+ default_display_frame_config: "FrameOptions | None"
+ """[Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the picture's
+ outline, over a white outline 3 wide with no margin (default None)."""
+
+
+class ImageMobjectFromCamera(MeshMobject):
+ """What a camera sees, as a picture: a rectangle showing the camera's view, drawn
+ anew every frame.
+
+ The picture is 3 units tall, in the frame's proportions. Move the camera's
+ [frame][manimgx.Camera.frame] to look elsewhere, scale it to zoom: the picture
+ follows. The camera sees everything but this picture; a
+ [ZoomedScene][manimgx.ZoomedScene] shows its zoomed camera's view with one.
+
+ Args:
+ camera: The camera whose view the picture shows.
+ default_display_frame_config: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions] for the
+ outline [add_display_frame][manimgx.ImageMobjectFromCamera.add_display_frame]
+ draws, over a white outline 3 wide with no margin.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class ImageMobjectFromCameraExample(m.Scene):
+ def construct(self) -> None:
+ square = m.Square(side_length=4, color=m.BLUE, fill_opacity=0.5)
+ self.add(square.shift(2 * m.LEFT + 0.5 * m.DOWN))
+ camera = m.Camera()
+ frame = camera.frame.scale(0.25).move_to(square.get_corner(m.UL))
+ frame.set_stroke(m.YELLOW, 3)
+ picture = m.ImageMobjectFromCamera(camera).add_display_frame()
+ self.add(frame, picture.to_corner(m.UR))
+ self.play(frame.animate.move_to(square.get_corner(m.DR)), run_time=3)
+ ```
+ """
+
+ # a quad textured with the camera's view (a camera's view is a texture)
+
+ def __init__(
+ self,
+ camera: "Camera",
+ default_display_frame_config: "FrameOptions | None" = None,
+ **kwargs: Unpack[Style],
+ ) -> None:
+ self.camera = camera
+ """The camera whose view the picture shows."""
+ frame: FrameOptions = {"stroke_width": 3, "stroke_color": WHITE, "buff": 0}
+ self.default_display_frame_config = frame | (default_display_frame_config or {})
+ w = (
+ 1.5 * config.frame_width / config.frame_height
+ ) # CE: 3 units high, the frame's aspect
+ super().__init__(
+ np.array(
+ [[-w, 1.5, 0], [w, 1.5, 0], [-w, -1.5, 0], [w, -1.5, 0]], dtype=float
+ ),
+ np.array([[0, 1, 2], [1, 3, 2]]),
+ uvs=np.array([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=float),
+ texture=camera,
+ **kwargs,
+ )
+
+ def add_display_frame(self, **kwargs: "Unpack[FrameOptions]") -> Self:
+ """Outline the picture: a surrounding rectangle, added as a submobject.
+
+ Args:
+ **kwargs: [Surrounding rectangle
+ keywords][manimgx.mobjects.annotations.FrameOptions], over
+ `default_display_frame_config`.
+ """
+ from manimgx.mobjects.annotations import SurroundingRectangle
+
+ self.display_frame = SurroundingRectangle(
+ self, **(self.default_display_frame_config | kwargs)
+ )
+ return self.add(self.display_frame)
diff --git a/src/manimgx/mobjects/lights.py b/src/manimgx/mobjects/lights.py
index beb5f694..94311a34 100644
--- a/src/manimgx/mobjects/lights.py
+++ b/src/manimgx/mobjects/lights.py
@@ -5,6 +5,8 @@ matte surface shows: 1 makes such a surface facing the light white."""
from __future__ import annotations
+from warnings import deprecated
+
__all__ = [
"AmbientLight",
"EnvironmentLight",
@@ -112,7 +114,9 @@ class SunLight(Light):
sun = m.SunLight(5 * m.RIGHT + 3 * m.OUT)
self.add(sun, m.AmbientLight(intensity=0.15))
self.add(m.Sphere(resolution=(48, 48)).set_material(m.Material()))
- self.play(m.Rotate(sun, m.PI, axis=m.OUT, about_point=m.ORIGIN), run_time=3)
+ self.play(
+ m.Rotate(sun, m.PI, axis=m.OUT, about_point=m.ORIGIN), run_time=3
+ )
```
"""
@@ -152,7 +156,9 @@ class PointLight(Light):
self.set_camera_orientation(phi=70 * m.DEGREES, theta=-30 * m.DEGREES)
lamp = m.PointLight(2 * m.OUT + 2 * m.LEFT, m.ORANGE, intensity=6)
self.add(lamp, m.AmbientLight(intensity=0.05))
- floor = m.Surface(lambda u, v: [u, v, -1], u_range=[-4, 4], v_range=[-4, 4])
+ floor = m.Surface(
+ lambda u, v: [u, v, -1], u_range=[-4, 4], v_range=[-4, 4]
+ )
self.add(floor.set_material(m.Material(roughness=0.4)))
self.play(lamp.animate.shift(4 * m.RIGHT), run_time=3)
```
@@ -195,8 +201,14 @@ class SpotLight(PointLight):
class SpotLightExample(m.ThreeDScene):
def construct(self) -> None:
self.set_camera_orientation(phi=60 * m.DEGREES, theta=-60 * m.DEGREES)
- self.add(m.SpotLight(4 * m.OUT, toward=m.ORIGIN, intensity=20, angle=m.PI / 8))
- floor = m.Surface(lambda u, v: [u, v, 0], u_range=[-4, 4], v_range=[-4, 4])
+ self.add(
+ m.SpotLight(
+ 4 * m.OUT, toward=m.ORIGIN, intensity=20, angle=m.PI / 8
+ )
+ )
+ floor = m.Surface(
+ lambda u, v: [u, v, 0], u_range=[-4, 4], v_range=[-4, 4]
+ )
self.add(floor.set_material(m.Material(roughness=0.7)))
```
"""
@@ -306,6 +318,7 @@ class EnvironmentLight(Light):
# its picture's right and up, a unit from its point: turned with it
self.add(VectorizedPoint(RIGHT), VectorizedPoint(OUT))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def axes(self) -> tuple[np.ndarray, np.ndarray]:
"""Its picture's `RIGHT` and up in the scene, as it is turned: unit vectors, at a right
angle."""
diff --git a/tests/unit/mobjects/test_images.py b/tests/unit/mobjects/test_images.py
new file mode 100644
index 00000000..37c7c2ed
--- /dev/null
+++ b/tests/unit/mobjects/test_images.py
@@ -0,0 +1,95 @@
+"""An image's pixels are the picture it shows: `pixel_array` is that picture, read-only,
+however the image was made, recolored, copied or became another. Recoloring paints a
+silhouette in the color, keeping each pixel's opacity unless it is given one; a copy recolors
+apart from its original; and the array an image was made of stays the caller's: the image
+holds a copy, which the array's changing later never reaches."""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+
+import numpy as np
+import pytest
+
+import manimgx as m
+
+PICTURE = np.array([[[10, 20, 30, 41], [50, 60, 70, 83]]], dtype=np.uint8)
+OTHER = np.full((2, 3, 4), 191, dtype=np.uint8)
+
+
+@dataclass(frozen=True)
+class Change:
+ do: Callable[[m.ImageMobject], m.ImageMobject]
+ source: np.ndarray # the picture it shows
+ color: m.ManimColor | None = None # the silhouette's, once recolored
+ alpha: float | None = None # every pixel's opacity, once one was given
+
+
+CHANGES = {
+ "made": Change(lambda image: image, PICTURE),
+ "recolored": Change(lambda image: image.set_color(m.BLUE), PICTURE, m.BLUE),
+ "recolored, at an opacity": Change(
+ lambda image: image.set_color(m.BLUE, alpha=0.5), PICTURE, m.BLUE, 0.5
+ ),
+ "recolored twice": Change(
+ lambda image: image.set_color(m.BLUE, alpha=0.5).set_color(m.RED),
+ PICTURE,
+ m.RED,
+ 0.5,
+ ),
+ "become another": Change(lambda image: image.become(m.ImageMobject(OTHER)), OTHER),
+ "become another, recolored": Change(
+ lambda image: image.become(m.ImageMobject(OTHER)).set_color(m.BLUE),
+ OTHER,
+ m.BLUE,
+ ),
+ "copied, recolored": Change(
+ lambda image: image.copy().set_color(m.GREEN, alpha=0.25),
+ PICTURE,
+ m.GREEN,
+ 0.25,
+ ),
+}
+
+
[email protected]("name", sorted(CHANGES))
+def test_an_images_pixels_are_the_picture_it_shows(name: str) -> None:
+ change = CHANGES[name]
+ pixels = PICTURE.copy()
+ original = m.ImageMobject(pixels)
+ image = change.do(original)
+ shown = np.asarray(image.paint.texture)
+ np.testing.assert_array_equal(image.pixel_array, shown)
+ assert not image.pixel_array.flags.writeable
+ expected = change.source.astype(int)
+ if change.color is not None:
+ expected[:, :, :3] = np.round(change.color.to_rgb() * 255)
+ if change.alpha is not None:
+ expected[:, :, 3] = round(255 * change.alpha)
+ np.testing.assert_allclose(shown.astype(int), expected, atol=1) # (to a level)
+ if image is not original: # (a copy recolors apart)
+ np.testing.assert_array_equal(original.pixel_array, PICTURE)
+ assert pixels.flags.writeable # (the array it was made of stays the caller's)
+
+
+TRIANGLE = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
+GIVEN = ("an array", "a read-only view", "read-only, with a writable alias")
+
+
[email protected]("size", [2, 8])
[email protected]("given", GIVEN)
[email protected]("meshed", [False, True], ids=["alone", "a mesh's texture too"])
+def test_an_images_pixels_are_its_own(given: str, size: int, meshed: bool) -> None:
+ owner = np.full((size, size, 4), 29, dtype=np.uint8)
+ alias = owner.view() # writable, whatever becomes of the rest
+ pixels = owner.view() if given == "a read-only view" else owner
+ if given != "an array":
+ pixels.flags.writeable = False
+ if meshed: # (a mesh textured with them first)
+ m.MeshMobject(TRIANGLE, np.array([[0, 1, 2]]), texture=pixels)
+ image = m.ImageMobject(pixels)
+ assert image.pixel_array is image.paint.texture
+ assert not np.shares_memory(image.pixel_array, owner)
+ alias[:] = 101
+ again = m.ImageMobject(np.full_like(owner, 29)) # (the pixels as they were)
+ for picture in (image, again):
+ np.testing.assert_array_equal(picture.pixel_array, np.full_like(owner, 29))