1+ import spatialdata as sd
2+ from spatialdata .transformations import Scale , Identity , set_transformation
3+
4+ def add_micron_coord_sys (sdata , pixel_size = None , z_step = None ):
5+ # Define the pixel scaling factor
6+ if pixel_size is None and 'table' in sdata :
7+ pixel_size = sdata ['table' ].uns ['section_metadata' ]['pixel_size' ]
8+ if z_step is None and 'table' in sdata :
9+ z_step = sdata ['table' ].uns ['section_metadata' ]['z_step_size' ]
10+ else :
11+ z_step = 1.0
12+
13+ # 2D Images (channel, y, x)
14+ # c = 1.0 (channels are discrete)
15+ scale_yx = Scale ([pixel_size , pixel_size ], axes = ("y" , "x" ))
16+ scale_cyx = Scale ([1.0 , pixel_size , pixel_size ], axes = ("c" , "y" , "x" ))
17+
18+ # For 3D Z-Stacks (c, z, y, x)
19+ # c = 1.0 (channels are discrete)
20+ # z = 3.0 (microns per plane)
21+ # y, x = 0.2125 (microns per pixel)
22+ scale_czyx = Scale (
23+ [1.0 , z_step , pixel_size , pixel_size ],
24+ axes = ("c" , "z" , "y" , "x" )
25+ )
26+
27+ # Identity transform for elements already in microns
28+ identity = Identity ()
29+
30+ # --- Images ---
31+ # dapi_zstack is (c, z, y, x)
32+ if 'dapi_zstack' in sdata .images :
33+ set_transformation (
34+ sdata .images ['dapi_zstack' ],
35+ scale_czyx ,
36+ to_coordinate_system = "microns"
37+ )
38+
39+ # morphology_focus is (c, y, x)
40+ if 'morphology_focus' in sdata .images :
41+ set_transformation (
42+ sdata .images ['morphology_focus' ],
43+ scale_cyx ,
44+ to_coordinate_system = "microns"
45+ )
46+
47+ # --- Labels ---
48+ # Both labels are (y, x)
49+ for label_name in sdata .labels :
50+ set_transformation (
51+ sdata .labels [label_name ],
52+ scale_yx ,
53+ to_coordinate_system = "microns"
54+ )
55+
56+ # --- Shapes & Points ---
57+ # Already in microns
58+ for shape_name in sdata .shapes :
59+ set_transformation (
60+ sdata .shapes [shape_name ],
61+ identity ,
62+ to_coordinate_system = "microns"
63+ )
64+
65+ for point_name in sdata .points :
66+ set_transformation (
67+ sdata .points [point_name ],
68+ identity ,
69+ to_coordinate_system = "microns"
70+ )
71+ return sdata
0 commit comments