Coverage for tests/res/multi_resolution_uint8_3channels.py: 100%

46 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-31 11:24 +0000

1import tifffile 

2import os 

3import numpy as np 

4from qubalab.images.metadata.image_shape import ImageShape 

5 

6 

7def get_name() -> str: 

8 return "multi_resolution_uint8_3channels.ome.tif" 

9 

10 

11def get_path() -> str: 

12 return os.path.realpath(os.path.join(os.path.realpath(__file__), os.pardir, get_name())) 

13 

14 

15def get_shapes() -> tuple[ImageShape, ...]: 

16 return ( 

17 ImageShape(512, 256, c=3), 

18 ImageShape(256, 128, c=3), 

19 ImageShape(128, 64, c=3), 

20 ImageShape(64, 32, c=3), 

21 ImageShape(32, 16, c=3), 

22 ImageShape(16, 8, c=3), 

23 ImageShape(8, 4, c=3), 

24 ) 

25 

26 

27def get_pixel_size_x_y_in_micrometers() -> float: 

28 return 0.25 

29 

30 

31def get_dtype(): 

32 return np.uint8 

33 

34 

35def get_downsamples() -> tuple[float, ...]: 

36 return tuple([get_shapes()[0].x / shape.x for shape in get_shapes()]) 

37 

38 

39def get_pixel_value(downsample: float, x: int, y: int, c: int) -> int: 

40 return pixels[..., ::int(downsample), ::int(downsample)][c, y, x] 

41 

42 

43def _get_pixels() -> np.array: 

44 width = get_shapes()[0].x 

45 height = get_shapes()[0].y 

46 

47 pixels = [] 

48 for c in range(get_shapes()[0].c): 

49 channel = [] 

50 for y in range(height): 

51 row = [] 

52 for x in range(width): 

53 if c == 0: 

54 row.append(int(255 * x / width)) 

55 elif c == 1: 

56 row.append(int(255 * y / height)) 

57 else: 

58 row.append(int(255 * x / width * y / height)) 

59 channel.append(row) 

60 pixels.append(channel) 

61 return np.array(pixels, get_dtype()) 

62 

63 

64def _write_image(pixels: np.array): 

65 metadata = { 

66 'PhysicalSizeX': get_pixel_size_x_y_in_micrometers(), 

67 'PhysicalSizeXUnit': 'µm', 

68 'PhysicalSizeY': get_pixel_size_x_y_in_micrometers(), 

69 'PhysicalSizeYUnit': 'µm' 

70 } 

71 

72 with tifffile.TiffWriter(get_path()) as tif: 

73 number_of_subresolutions = len(get_downsamples())-1 

74 number_of_pixels_per_cm = 1e4 / get_pixel_size_x_y_in_micrometers() 

75 

76 tif.write( 

77 pixels, 

78 metadata=metadata, 

79 subifds=number_of_subresolutions, 

80 resolution=(number_of_pixels_per_cm, number_of_pixels_per_cm), 

81 resolutionunit=3, # indicate that the resolution above is in cm^-1, 

82 photometric='rgb', 

83 tile=(128, 128) 

84 ) 

85 

86 # Write sub resolutions 

87 for downsample in get_downsamples(): 

88 if downsample > 1: 

89 tif.write( 

90 pixels[..., ::int(downsample), ::int(downsample)], 

91 metadata=metadata, 

92 subfiletype=1, # indicate that the image is part of a multi-page image 

93 resolution=(number_of_pixels_per_cm / downsample, number_of_pixels_per_cm / downsample), 

94 resolutionunit=3, 

95 photometric='rgb', 

96 tile=(128, 128) 

97 ) 

98 

99 

100pixels = _get_pixels() 

101_write_image(pixels)