Cropping spatialdata to extent of shapes

scanpy.pl.spatial has an option crop=None that automatically crops the image to the extent of the shapes:

Coordinates to use for cropping the image (left, right, top, bottom). These coordinates are expected to be in pixel space (same as basis ) and will be transformed by scale_factor . If not provided, image is automatically cropped to bounds of basis , plus a border.

I find this a very useful default for Cytassist visium samples, because the majority of the image will be empty space plus the fiducial frame. In spatialdata, I could probably do a bounding box query to achieve something similar. But how would I get the coordinates of the respective bounding box?

Hi, you can use the get_extent() function to get the bounding box of the shapes. Then add a transformation to the bounding box (the .inverse() one between the shapes and the image you want to crop). This transformation can be obtained with transform_to_coordinate_system().

1 Like

In alternative you can call rasterize() and pass the min_coordinate, max_coordinate of the bounding box in the target_coordinate_system. This will give you the image you want if you are ok of getting it downscaled.

1 Like