File size: 8,387 Bytes
18d9fce
72afcb8
18d9fce
 
 
 
 
 
 
 
1ec5a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d9fce
 
 
 
 
 
1ec5a7d
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
1ec5a7d
 
 
 
 
07cafd6
1ec5a7d
 
18d9fce
 
07cafd6
1ec5a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d9fce
 
07cafd6
1ec5a7d
 
18d9fce
 
 
1ec5a7d
18d9fce
 
1ec5a7d
 
18d9fce
1ec5a7d
 
18d9fce
 
 
 
 
 
 
 
 
 
 
 
 
1ec5a7d
 
 
 
18d9fce
 
 
 
 
 
 
 
 
 
 
1ec5a7d
18d9fce
 
1ec5a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d9fce
 
1ec5a7d
18d9fce
 
 
1ec5a7d
 
18d9fce
 
 
 
 
 
1ec5a7d
18d9fce
 
 
1ec5a7d
 
18d9fce
 
 
 
 
 
1ec5a7d
18d9fce
 
 
1ec5a7d
 
18d9fce
 
 
 
1ec5a7d
18d9fce
 
 
1ec5a7d
 
18d9fce
1ec5a7d
 
 
 
 
18d9fce
 
 
 
 
 
 
1ec5a7d
 
18d9fce
 
 
 
 
 
1ec5a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18d9fce
 
1ec5a7d
 
 
 
18d9fce
1ec5a7d
 
18d9fce
 
1ec5a7d
 
 
 
 
 
 
 
 
 
 
 
 
 
18d9fce
 
 
 
 
1ec5a7d
 
18d9fce
 
 
1ec5a7d
 
 
 
 
72afcb8
 
1ec5a7d
72afcb8
1ec5a7d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import streamlit as st
from streamlit.components.v1 import html
import matplotlib

try:
    from imageio.v2 import imread
except:
    from imageio import imread
import matplotlib.pyplot as plt
from stardist import random_label_cmap
from myoquant.src.common_func import (
    load_cellpose,
    load_stardist,
    run_cellpose,
    run_stardist,
    is_gpu_availiable,
    df_from_cellpose_mask,
    df_from_stardist_mask,
)
from myoquant.src.HE_analysis import (
    predict_all_cells,
    extract_ROIs,
    single_cell_analysis,
    paint_histo_img,
)

st.set_page_config(
    page_title="MyoQuant HE Analysis",
    page_icon="🔬",
)

use_GPU = is_gpu_availiable()


@st.cache_resource
def st_load_cellpose():
    return load_cellpose()


@st.cache_resource
def st_load_stardist():
    return load_stardist()


@st.cache_data
def st_run_cellpose(image_ndarray, _model):
    return run_cellpose(image_ndarray, _model)


@st.cache_data
def st_run_stardist(image_ndarray, _model, nms_thresh, prob_thresh):
    return run_stardist(image_ndarray, _model, nms_thresh, prob_thresh)


@st.cache_data
def st_df_from_cellpose_mask(mask):
    return df_from_cellpose_mask(mask)


@st.cache_data
def st_df_from_stardist_mask(mask):
    return df_from_stardist_mask(mask)


@st.cache_data
def st_predict_all_cells(
    image_ndarray, df_cellpose, mask_stardist, internalised_threshold
):
    return predict_all_cells(
        image_ndarray, df_cellpose, mask_stardist, internalised_threshold
    )


@st.cache_data
def st_extract_ROIs(image_ndarray, selected_fiber, df_cellpose, mask_stardist):
    return extract_ROIs(image_ndarray, selected_fiber, df_cellpose, mask_stardist)


@st.cache_data
def st_single_cell_analysis(
    single_cell_img,
    single_cell_mask,
    df_nuc_single,
    x_fiber,
    y_fiber,
    selected_fiber,
    internalised_threshold,
    draw_and_return=True,
):
    return single_cell_analysis(
        single_cell_img,
        single_cell_mask,
        df_nuc_single,
        x_fiber,
        y_fiber,
        selected_fiber + 1,
        internalised_threshold,
        draw_and_return=True,
    )


@st.cache_data
def st_paint_histo_img(image_ndarray, df_cellpose, cellpose_df_stat):
    return paint_histo_img(image_ndarray, df_cellpose, cellpose_df_stat)


with st.sidebar:
    st.write("Nuclei detection Parameters (Stardist)")
    nms_thresh = st.slider("Stardist NMS Tresh", 0.0, 1.0, 0.4, 0.1)
    prob_thresh = st.slider("Stardist Prob Tresh", 0.5, 1.0, 0.5, 0.05)
    st.write("Nuclei Classification Parameter")
    eccentricity_thresh = st.slider("Eccentricity Score Tresh", 0.0, 1.0, 0.75, 0.05)

model_cellpose = st_load_cellpose()
model_stardist = st_load_stardist()

st.title("HE Staining Analysis")
st.write(
    "This demo will automatically detect cells and nucleus in the image and try to quantify a certain number of features."
)
st.write("Upload your HE Staining image")
uploaded_file = st.file_uploader("Choose a file")

if uploaded_file is not None:
    image_ndarray = imread(uploaded_file)
    st.write("Raw Image")
    image = st.image(uploaded_file)

    mask_cellpose = st_run_cellpose(image_ndarray, model_cellpose)
    mask_stardist = st_run_stardist(
        image_ndarray, model_stardist, nms_thresh, prob_thresh
    )
    mask_stardist_copy = mask_stardist.copy()
    st.header("Segmentation Results")
    st.subheader("CellPose and Stardist overlayed results")
    fig, ax = plt.subplots(1, 1)
    ax.imshow(mask_cellpose, cmap="viridis")
    lbl_cmap = random_label_cmap()
    ax.imshow(mask_stardist, cmap=lbl_cmap, alpha=0.5)
    ax.axis("off")
    st.pyplot(fig)

    st.subheader("All cells detected by CellPose")
    df_cellpose = st_df_from_cellpose_mask(mask_cellpose)

    st.header("Full Nucleus Analysis Results")
    cellpose_df_stat, all_nuc_df_stats = st_predict_all_cells(
        image_ndarray,
        df_cellpose,
        mask_stardist,
        internalised_threshold=eccentricity_thresh,
    )
    st.dataframe(
        cellpose_df_stat.drop(
            [
                "centroid-0",
                "centroid-1",
                "bbox-0",
                "bbox-1",
                "bbox-2",
                "bbox-3",
                "image",
            ],
            axis=1,
        )
    )
    st.write("Total number of nucleus : ", cellpose_df_stat["N° Nuc"].sum())
    st.write(
        "Total number of internalized nucleus : ",
        cellpose_df_stat["N° Nuc Intern"].sum(),
        " (",
        round(
            100
            * cellpose_df_stat["N° Nuc Intern"].sum()
            / cellpose_df_stat["N° Nuc"].sum(),
            2,
        ),
        "%)",
    )
    st.write(
        "Total number of peripherical nucleus : ",
        cellpose_df_stat["N° Nuc Periph"].sum(),
        " (",
        round(
            100
            * cellpose_df_stat["N° Nuc Periph"].sum()
            / cellpose_df_stat["N° Nuc"].sum(),
            2,
        ),
        "%)",
    )
    st.write(
        "Number of cell with at least one internalized nucleus : ",
        cellpose_df_stat["N° Nuc Intern"].astype(bool).sum(axis=0),
        " (",
        round(
            100
            * cellpose_df_stat["N° Nuc Intern"].astype(bool).sum(axis=0)
            / len(cellpose_df_stat),
            2,
        ),
        "%)",
    )

    st.header("Single Nucleus Analysis Details")
    selected_fiber = st.selectbox("Select a cell", list(range(len(df_cellpose))))
    selected_fiber = int(selected_fiber)
    (
        single_cell_img,
        nucleus_single_cell_img,
        single_cell_mask,
        df_nuc_single,
    ) = st_extract_ROIs(image_ndarray, selected_fiber, df_cellpose, mask_stardist)

    # df_nuc_single = df_from_stardist_mask(mask_stardist)
    st.markdown(
        """
        * White point represent cell centroid. 
        * Green point represent nucleus centroid. Green dashed line represent the fiber centrer - nucleus distance. 
        * Red point represent the cell border from a straight line between the cell centroid and the nucleus centroid. The red dashed line represent distance between the nucelus and the cell border. 
        * The periphery ratio is calculated by the division of the distance centroid - nucleus and the distance centroid - cell border."""
    )

    fig2, (ax1, ax2) = plt.subplots(1, 2)
    ax1.imshow(single_cell_img)
    ax2.imshow(nucleus_single_cell_img, cmap="viridis")
    # Plot Fiber centroid
    x_fiber = df_cellpose.iloc[selected_fiber, 3] - df_cellpose.iloc[selected_fiber, 6]
    y_fiber = df_cellpose.iloc[selected_fiber, 2] - df_cellpose.iloc[selected_fiber, 5]

    (
        n_nuc,
        n_nuc_intern,
        n_nuc_periph,
        df_nuc_single_stats,
        ax_nuc,
    ) = st_single_cell_analysis(
        single_cell_img,
        single_cell_mask,
        df_nuc_single,
        x_fiber,
        y_fiber,
        selected_fiber + 1,
        internalised_threshold=eccentricity_thresh,
        draw_and_return=True,
    )
    for index, value in df_nuc_single_stats.iterrows():
        st.write("Nucleus #{} has a periphery ratio of: {}".format(index, value[12]))
    ax1.axis("off")
    ax2.axis("off")
    # st.pyplot(fig2)
    ax_nuc.imshow(single_cell_img)
    ax_nuc.imshow(nucleus_single_cell_img, cmap="viridis", alpha=0.5)
    f = ax_nuc.figure

    st.pyplot(fig2)
    st.pyplot(f)
    st.subheader("All nucleus inside selected cell")

    st.dataframe(
        df_nuc_single_stats.drop(
            [
                "centroid-0",
                "centroid-1",
                "bbox-0",
                "bbox-1",
                "bbox-2",
                "bbox-3",
                "image",
            ],
            axis=1,
        )
    )

    st.header("Painted predicted image")
    st.write(
        "Green color indicates cells with only peripherical nuclei, red color indicates cells with at least one internal nucleus."
    )
    painted_img = st_paint_histo_img(image_ndarray, df_cellpose, cellpose_df_stat)
    fig4, ax4 = plt.subplots(1, 1)
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
        "", ["white", "green", "red"]
    )
    ax4.imshow(image_ndarray)
    ax4.imshow(painted_img, cmap=cmap, alpha=0.5)
    ax4.axis("off")
    st.pyplot(fig4)

html(
    f"""
    <script defer data-domain="lbgi.fr/myoquant" src="https://plausible.cmeyer.fr/js/script.js"></script>
    """
)