1414from anndata import AnnData
1515from geopandas import GeoDataFrame
1616from matplotlib .testing .compare import compare_images
17+ from PIL import Image
1718from shapely .geometry import MultiPolygon , Polygon
1819from spatialdata import SpatialData
1920from spatialdata .datasets import blobs , raccoon
3637ACTUAL = HERE / "figures"
3738TOL = 15
3839DPI = 80
40+ CANVAS_WIDTH = 400
41+ CANVAS_HEIGHT = 300
42+ _RESAMPLE = Image .Resampling .LANCZOS if hasattr (Image , "Resampling" ) else Image .LANCZOS
3943
4044
4145def 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 ()
4768def 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