Skip to content

Commit 1c11911

Browse files
committed
resizing test again
1 parent eecbbc9 commit 1c11911

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

tests/conftest.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from anndata import AnnData
1515
from geopandas import GeoDataFrame
1616
from matplotlib.testing.compare import compare_images
17+
from PIL import Image
1718
from shapely.geometry import MultiPolygon, Polygon
1819
from spatialdata import SpatialData
1920
from spatialdata.datasets import blobs, raccoon
@@ -36,13 +37,33 @@
3637
ACTUAL = HERE / "figures"
3738
TOL = 15
3839
DPI = 80
40+
CANVAS_WIDTH = 400
41+
CANVAS_HEIGHT = 300
42+
_RESAMPLE = Image.Resampling.LANCZOS if hasattr(Image, "Resampling") else Image.LANCZOS
3943

4044

4145
def get_standard_RNG():
4246
# we init from scratch each time to ensure same results in each test
4347
return np.random.default_rng(seed=42)
4448

4549

50+
def _resize_and_pad_image(path: Path, canvas_size: tuple[int, int] = (CANVAS_WIDTH, CANVAS_HEIGHT)) -> None:
51+
"""Scale image to fit canvas while keeping aspect ratio, then pad."""
52+
with Image.open(path) as img:
53+
img = img.convert("RGBA")
54+
target_w, target_h = canvas_size
55+
if img.width == 0 or img.height == 0:
56+
raise ValueError("Cannot resize image with zero dimension.")
57+
scale = min(target_w / img.width, target_h / img.height)
58+
new_w = max(1, int(round(img.width * scale)))
59+
new_h = max(1, int(round(img.height * scale)))
60+
resized = img.resize((new_w, new_h), resample=_RESAMPLE)
61+
canvas = Image.new("RGBA", canvas_size, (255, 255, 255, 255))
62+
offset = ((target_w - new_w) // 2, (target_h - new_h) // 2)
63+
canvas.paste(resized, offset, resized)
64+
canvas.convert("RGB").save(path)
65+
66+
4667
@pytest.fixture()
4768
def full_sdata() -> SpatialData:
4869
return SpatialData(
@@ -412,7 +433,7 @@ def compare(cls, basename: str, tolerance: float | None = None):
412433
ACTUAL.mkdir(parents=True, exist_ok=True)
413434
out_path = ACTUAL / f"{basename}.png"
414435

415-
width, height = 400, 300 # base dimensions; actual PNG may grow/shrink
436+
width, height = CANVAS_WIDTH, CANVAS_HEIGHT # base dimensions; actual PNG may grow/shrink
416437
fig = plt.gcf()
417438
fig.set_size_inches(width / DPI, height / DPI)
418439
fig.set_dpi(DPI)
@@ -439,6 +460,7 @@ def compare(cls, basename: str, tolerance: float | None = None):
439460
bbox_inches="tight",
440461
pad_inches=0.02, # small margin around everything
441462
)
463+
_resize_and_pad_image(out_path, (width, height))
442464
plt.close(fig)
443465

444466
if tolerance is None:

0 commit comments

Comments
 (0)