Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion tests/test_io_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
import pytest
from PIL import Image

from zea.io_lib import load_image, load_video, save_image, save_video
from zea.io_lib import (
compute_global_palette_by_histogram,
load_image,
load_video,
save_image,
save_to_gif,
save_video,
)

from . import DEFAULT_TEST_SEED

Expand Down Expand Up @@ -253,6 +260,39 @@ def test_color_palette(tmp_path):
assert loaded_with_palette_gif.shape == (n_frames, height, width)


def test_global_palette_keeps_exact_colors():
"""A histogram bin holding a single color is represented by exactly that color.

The palette entry is the mean of the colors in the bin, not the bin's center: a
center would round pure black to (4, 4, 4) at the default 5 bits per channel,
which is visibly not black wherever a plot's background is meant to be.
"""
colors = np.array([[0, 0, 0], [255, 255, 255], [130, 40, 200]], dtype=np.uint8)
image = Image.fromarray(np.repeat(colors[None], 4, axis=0))

palette = compute_global_palette_by_histogram([image], bits_per_channel=5)
entries = np.array(palette.getpalette(), dtype=np.uint8).reshape(-1, 3)

for color in colors:
assert (entries == color).all(axis=1).any(), f"{color} is not in the palette"


def test_save_to_gif_keeps_black_black(tmp_path):
"""A black background survives the shared-palette quantization as exactly 0."""
rng = np.random.default_rng(DEFAULT_TEST_SEED)
frames = np.zeros((4, 16, 16, 3), dtype=np.uint8)
# Something for the palette to spend its other entries on, so black is not the
# only color and has to survive alongside the rest.
frames[:, 4:12, 4:12] = rng.integers(0, 255, (4, 8, 8, 3), dtype=np.uint8)

path = tmp_path / "black_background.gif"
save_to_gif(frames, path, fps=10, shared_color_palette=True)

loaded = load_video(path, mode="RGB")
background = np.concatenate([loaded[:, :4].ravel(), loaded[:, 12:].ravel()])
assert background.max() == 0


def test_animate_images_parameters_without_extent(tmp_path):
"""animate_images must not raise AttributeError when the parameters object has
no extent_imshow attribute (e.g. a minimal or mock Parameters object)."""
Expand Down
34 changes: 23 additions & 11 deletions zea/io_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def save_video(images, filename, fps=20, **kwargs):
raise ValueError(f"Unsupported file extension: {ext}")


def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent=False):
def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent=False, loop=0):
"""Saves a sequence of images to a GIF file.

.. note::
Expand All @@ -198,6 +198,9 @@ def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent
throughout the GIF. Defaults to True, which is default behavior
of PIL.Image.save. Note: True increases speed and shrinks file
size for longer sequences.
loop (int, optional): Number of times to repeat after the first play.
Defaults to 0, which loops forever. Pass None to write no loop
extension at all, so the GIF plays once and stops on the last frame.
transparent (bool, optional): If True, keeps the alpha channel of RGBA
images as GIF transparency. GIF only supports binary transparency,
so pixels with alpha < 128 become fully transparent and all others
Expand Down Expand Up @@ -256,15 +259,18 @@ def save_to_gif(images, filename, fps=20, shared_color_palette=True, transparent

pillow_img, *pillow_imgs = pillow_imgs

# Pillow only omits the Netscape loop extension when `loop` is absent entirely
loop_kwarg = {} if loop is None else {"loop": loop}

pillow_img.save(
fp=filename,
format="GIF",
append_images=pillow_imgs,
save_all=True,
loop=0,
duration=duration,
interlace=False,
optimize=False,
**loop_kwarg,
**transparency_kwargs,
)
log.success(f"Successfully saved GIF to -> {log.yellow(filename)}")
Expand Down Expand Up @@ -428,6 +434,8 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette
total_bins = bins_per**3
# counts per bin in the final histogram
counts = np.zeros(total_bins, dtype=np.int64)
# per-bin sum of the colors that landed in it, to average into its entry
sums = np.zeros((total_bins, 3), dtype=np.int64)

shift = 8 - bits_per_channel
# Iterate images, accumulate bin counts
Expand All @@ -441,23 +449,27 @@ def compute_global_palette_by_histogram(pillow_imgs, bits_per_channel=5, palette
# accumulate counts
bincount = np.bincount(idx, minlength=total_bins)
counts += bincount
for channel in range(3):
sums[:, channel] += np.bincount(
idx, weights=arr[:, channel], minlength=total_bins
).astype(np.int64)

# pick top bins
top_idx = np.argpartition(-counts, palette_size - 1)[:palette_size]

# sort top bins by frequency
top_idx = top_idx[np.argsort(-counts[top_idx])]

# convert bin index back to representative RGB (center of bin)
bins = np.array(
[((i // (bins_per * bins_per)), (i // bins_per) % bins_per, i % bins_per) for i in top_idx]
# Represent each bin by the mean of the colors in it, not by the bin's center: a
# bin holding one exact color is then reproduced exactly, which matters most for
# the flat backgrounds that dominate plots -- a pure black one quantized to the
# center of its bin comes out a visibly non-black (4, 4, 4).
Comment thread
wesselvannierop marked this conversation as resolved.
Resolved
occupied = counts[top_idx] > 0
mean = np.zeros((len(top_idx), 3), dtype=np.uint8)
mean[occupied] = np.round(sums[top_idx][occupied] / counts[top_idx][occupied, None]).astype(
np.uint8
)

# expand bin centers back to 8-bit values
center = (
(bins * (1 << (8 - bits_per_channel)) + (1 << (7 - bits_per_channel))).clip(0, 255)
).astype(np.uint8)
palette_colors = center.reshape(-1, 3) # shape (k,3)
palette_colors = mean.reshape(-1, 3) # shape (k,3)

# build a PIL 'P' palette image from these colors
pal = np.zeros(768, dtype=np.uint8) # 256*3 entries
Expand Down
Loading