SPACEc 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,144 @@
1
+ import os
2
+
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ import pandas as pd
6
+ import tifffile
7
+ from scipy import ndimage as ndi
8
+ from skimage.filters import sobel
9
+ from skimage.segmentation import watershed
10
+
11
+
12
+ def label_tissue(
13
+ resized_im,
14
+ lower_cutoff=0.012,
15
+ upper_cutoff=0.025,
16
+ savefig=False,
17
+ showfig=True,
18
+ output_dir="./",
19
+ output_fname="",
20
+ ):
21
+ """
22
+ Label the tissue in the given image.
23
+
24
+ Parameters
25
+ ----------
26
+ resized_im : ndarray
27
+ The resized image to label.
28
+ lower_cutoff : float, optional
29
+ The lower cutoff for the sobel filter, by default 0.012.
30
+ upper_cutoff : float, optional
31
+ The upper cutoff for the sobel filter, by default 0.025.
32
+ savefig : bool, optional
33
+ Whether to save the figure or not, by default False.
34
+ showfig : bool, optional
35
+ Whether to show the figure or not, by default True.
36
+ output_dir : str, optional
37
+ The directory to save the figure in, by default "./".
38
+ output_fname : str, optional
39
+ The filename to save the figure as, by default "".
40
+
41
+ Returns
42
+ -------
43
+ DataFrame
44
+ A DataFrame containing the labels from the segmentation.
45
+ """
46
+ # cut off
47
+ elevation_map = sobel(resized_im)
48
+ markers = np.zeros_like(resized_im, dtype=int)
49
+ markers[resized_im <= lower_cutoff] = 1
50
+ markers[resized_im >= upper_cutoff] = 2
51
+
52
+ segmentation = watershed(elevation_map, markers)
53
+ # plt.imshow(segmentation)
54
+ # plt.title('Segmented tissues')
55
+ # plt.show()
56
+
57
+ segmentation = ndi.binary_fill_holes(segmentation - 1)
58
+ # plt.imshow(segmentation)
59
+ # plt.title('Segmented tissues with holes filled')
60
+ # plt.show()
61
+
62
+ # visualize initial identified segmented masks
63
+ labeled_tissues, _ = ndi.label(segmentation)
64
+ print(f"Identified {len(np.unique(labeled_tissues)) - 1} tissue pieces")
65
+ fig, axs = plt.subplots(1, 1)
66
+ axs.imshow(labeled_tissues)
67
+ axs.set_title("Labeled tissues")
68
+
69
+ if showfig:
70
+ if savefig:
71
+ fig.savefig(
72
+ output_dir + output_fname + "_labeled_seg_tissue_plot.pdf",
73
+ bbox_inches="tight",
74
+ )
75
+ else:
76
+ plt.show()
77
+
78
+ #######Non clustering option
79
+ print("Saving the labels from the segmentation!")
80
+ idx = np.nonzero(labeled_tissues)
81
+ vals = labeled_tissues[idx]
82
+ tissueframe = pd.DataFrame(vals, columns=["tissue"])
83
+ tissueframe["y"] = idx[0]
84
+ tissueframe["x"] = idx[1]
85
+ tissueframe["region1"] = tissueframe["tissue"]
86
+
87
+ return tissueframe
88
+
89
+
90
+ def save_labelled_tissue(
91
+ filepath,
92
+ tissueframe,
93
+ region="region", # this can be 'region1' if you didn't manually rename your tissue region
94
+ padding=50,
95
+ downscale_factor=64,
96
+ output_dir="./",
97
+ output_fname="",
98
+ ):
99
+ """
100
+ Save the labelled tissue from the given image.
101
+
102
+ Parameters
103
+ ----------
104
+ filepath : str
105
+ The path to the image file.
106
+ tissueframe : DataFrame
107
+ The DataFrame containing the labels from the segmentation.
108
+ region : str, optional
109
+ The region to group by, by default "region".
110
+ padding : int, optional
111
+ The padding to add to the extracted tissue, by default 50.
112
+ downscale_factor : int, optional
113
+ The factor to downscale the image by, by default 64.
114
+ output_dir : str, optional
115
+ The directory to save the image in, by default "./".
116
+ output_fname : str, optional
117
+ The filename to save the image as, by default "".
118
+
119
+ Returns
120
+ -------
121
+ None
122
+ """
123
+ tissueframe2 = tissueframe.groupby(region).agg([min, max])
124
+ print("Reading in the qptiff file, might take awhile!")
125
+ currim = tifffile.imread(filepath)
126
+
127
+ for index, row in tissueframe2.iterrows():
128
+ ymin = row["y"]["min"] * downscale_factor
129
+ ymax = row["y"]["max"] * downscale_factor
130
+ xmin = row["x"]["min"] * downscale_factor
131
+ xmax = row["x"]["max"] * downscale_factor
132
+ ymin = max(ymin - padding, 0)
133
+ ymax = min(ymax + padding, currim.shape[1])
134
+ xmin = max(xmin - padding, 0)
135
+ xmax = min(xmax + padding, currim.shape[2])
136
+ subim = currim[:, ymin:ymax, xmin:xmax]
137
+ outpath = os.path.join(
138
+ output_dir, output_fname, f"reg00{index}_X01_Y01_Z01.tif"
139
+ )
140
+ plt.imshow(subim[0])
141
+ plt.title(f"Extracting tissue {index}: ")
142
+ plt.show()
143
+ print(f"Saving tissue image at {outpath}")
144
+ tifffile.imwrite(outpath, subim)