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,895 @@
1
+ import os
2
+ import pathlib
3
+ import shutil
4
+ import sys
5
+
6
+ import cv2
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import pandas as pd
10
+ import requests
11
+ import skimage.io
12
+ import tensorflow as tf
13
+ from cellpose import io, models
14
+ from deepcell.applications import Mesmer
15
+ from deepcell.utils.plot_utils import create_rgb_image, make_outline_overlay
16
+ from skimage.measure import regionprops_table
17
+ from tensorflow.keras.models import load_model
18
+ from tqdm import tqdm
19
+
20
+ from .._shared.segmentation import (
21
+ combine_channels,
22
+ create_multichannel_tiff,
23
+ format_CODEX,
24
+ )
25
+
26
+
27
+ def cell_segmentation(
28
+ file_name,
29
+ channel_file,
30
+ output_dir,
31
+ output_fname="",
32
+ seg_method="mesmer",
33
+ nuclei_channel="DAPI",
34
+ input_format="Multichannel", # CODEX or Multichannel --> This depends on the machine you are using and the resulting file format (see documentation above)
35
+ membrane_channel_list=None,
36
+ size_cutoff=0, # quantificaition
37
+ compartment="whole-cell", # mesmer # segment whole cells or nuclei only
38
+ plot_predictions=True, # mesmer # plot segmentation results
39
+ model="cyto3", # cellpose
40
+ use_gpu=True, # cellpose
41
+ cytoplasm_channel_list=None, # celpose
42
+ diameter=None, # cellpose
43
+ save_mask_as_png=False, # cellpose
44
+ model_path="./models",
45
+ resize_factor=1,
46
+ custom_model=False,
47
+ differentiate_nucleus_cytoplasm=False, # experimental
48
+ ):
49
+ """
50
+ Perform cell segmentation on an image.
51
+ Parameters
52
+ ----------
53
+ file_name : str
54
+ The path to the image file.
55
+ channel_file : str
56
+ The path to the file containing the channel names.
57
+ output_dir : str
58
+ The directory where the output will be saved.
59
+ output_fname : str, optional
60
+ The name of the output file. Default is an empty string.
61
+ seg_method : str
62
+ The segmentation method to use. Options are 'mesmer' and 'cellpose'. Default is 'mesmer'.
63
+ nuclei_channel : str
64
+ The name of the nuclei channel. Default is 'DAPI'.
65
+ input_format : str
66
+ The input_format used to generate the image. Options are 'CODEX' and 'Multichannel'. Default is 'Multichannel'.
67
+ membrane_channel_list : list of str, optional
68
+ The names of the membrane channels.
69
+ size_cutoff : int, optional
70
+ The size cutoff for segmentation. Default is 0.
71
+ compartment : str, optional
72
+ The compartment to segment. Options are 'whole-cell' and 'nuclei'. Default is 'whole-cell'. This only applies to Mesmer.
73
+ plot_predictions : bool, optional
74
+ Whether to plot the segmentation results. Default is True.
75
+ model : str, optional
76
+ The model to use for segmentation. Default is 'tissuenet'. This only applies to Cellpose.
77
+ use_gpu : bool, optional
78
+ Whether to use GPU for segmentation. Default is True. This only applies to Cellpose.
79
+ cytoplasm_channel_list : list of str, optional
80
+ The names of the cytoplasm channels.
81
+ diameter : int, optional
82
+ The diameter of the cells. Default is None - if set to None the diameter is automatically defined. This only applies to Cellpose.
83
+ save_mask_as_png : bool, optional
84
+ Whether to save the segmentation mask as a PNG file. Default is False.
85
+ model_path : str, optional
86
+ The path to the model. Default is './models'.
87
+ differentiate_nucleus_cytoplasm : bool, optional
88
+ Whether to differentiate between nucleus and cytoplasm. Default is False.
89
+ Returns
90
+ -------
91
+ dict
92
+ A dictionary containing the original image ('img'), the segmentation masks ('masks'), and the image dictionary ('image_dict').
93
+ """
94
+ if use_gpu == True:
95
+ gpus = tf.config.list_physical_devices("GPU")
96
+
97
+ if gpus:
98
+ print("GPU(s) available")
99
+ for gpu in gpus:
100
+ tf.config.experimental.set_memory_growth(gpu, True)
101
+
102
+ print("Create image channels!")
103
+
104
+ # check input format
105
+ if input_format not in ["CODEX", "Multichannel", "Channels"]:
106
+ sys.exit(
107
+ "Please provide a valid input format (Multichannel, Channels or CODEX)!"
108
+ )
109
+
110
+ if input_format != "Channels":
111
+ # Load the image
112
+ img = skimage.io.imread(file_name)
113
+ # Read channels and store as list
114
+ with open(channel_file, "r") as f:
115
+ channel_names = f.read().splitlines()
116
+ # Function reads channels and stores them as a dictionary (storing as a dictionary allows to select specific channels by name)
117
+ image_dict = format_CODEX(
118
+ image=img,
119
+ channel_names=channel_names, # file with list of channel names (see channelnames.txt)
120
+ input_format=input_format,
121
+ )
122
+ else:
123
+ image_dict = format_CODEX(
124
+ image=file_name,
125
+ channel_names=None, # file with list of channel names (see channelnames.txt)
126
+ input_format=input_format,
127
+ )
128
+ channel_names = list(image_dict.keys())
129
+ # Generate image for segmentation
130
+ if membrane_channel_list is not None:
131
+ image_dict = combine_channels(
132
+ image_dict, membrane_channel_list, new_channel_name="segmentation_channel"
133
+ ) # combine channels for better segmentation. In this example we combine channels to get a membrane outline for all cells in the image
134
+ segmentation_channels = [
135
+ nuclei_channel,
136
+ "segmentation_channel",
137
+ ] # replace with your actual channel names
138
+ segmentation_image_dict = {
139
+ channel: image_dict[channel]
140
+ for channel in segmentation_channels
141
+ if channel in image_dict
142
+ }
143
+ # Iterate over the dictionary
144
+ for channel, img in segmentation_image_dict.items():
145
+ # Calculate the new dimensions
146
+ new_width = int(img.shape[1] * resize_factor)
147
+ new_height = int(img.shape[0] * resize_factor)
148
+ # Resize the image
149
+ resized_img = cv2.resize(
150
+ img, (new_width, new_height), interpolation=cv2.INTER_AREA
151
+ )
152
+ # Replace the original image with the resized image in the dictionary
153
+ segmentation_image_dict[channel] = resized_img
154
+
155
+ if differentiate_nucleus_cytoplasm == True:
156
+ if membrane_channel_list == None:
157
+ print(
158
+ "Provide membrane channel for differentiation between nucleus and cytoplasm"
159
+ )
160
+ return
161
+ else:
162
+ if seg_method == "mesmer":
163
+ print("Segmenting with Mesmer!")
164
+
165
+ masks_nuclei = mesmer_segmentation(
166
+ nuclei_image=segmentation_image_dict[nuclei_channel],
167
+ membrane_image=None,
168
+ plot_predictions=plot_predictions, # plot segmentation results
169
+ compartment="nuclear",
170
+ model_path=model_path,
171
+ ) # segment whole cells or nuclei only
172
+
173
+ masks_whole_cell = mesmer_segmentation(
174
+ nuclei_image=segmentation_image_dict[nuclei_channel],
175
+ membrane_image=segmentation_image_dict["segmentation_channel"],
176
+ plot_predictions=plot_predictions, # plot segmentation results
177
+ compartment=compartment,
178
+ model_path=model_path,
179
+ ) # segment whole cells or nuclei only
180
+ else:
181
+ print("Segmenting with Cellpose!")
182
+
183
+ (
184
+ masks_nuclei,
185
+ flows,
186
+ styles,
187
+ input_image,
188
+ rgb_channels,
189
+ ) = cellpose_segmentation(
190
+ image_dict=segmentation_image_dict,
191
+ output_dir=output_dir,
192
+ membrane_channel=None,
193
+ cytoplasm_channel=cytoplasm_channel_list,
194
+ nucleus_channel=nuclei_channel,
195
+ use_gpu=use_gpu,
196
+ model=model,
197
+ custom_model=custom_model,
198
+ diameter=diameter,
199
+ save_mask_as_png=save_mask_as_png,
200
+ )
201
+
202
+ (
203
+ masks_whole_cell,
204
+ flows,
205
+ styles,
206
+ input_image,
207
+ rgb_channels,
208
+ ) = cellpose_segmentation(
209
+ image_dict=segmentation_image_dict,
210
+ output_dir=output_dir,
211
+ membrane_channel="segmentation_channel",
212
+ cytoplasm_channel=cytoplasm_channel_list,
213
+ nucleus_channel=nuclei_channel,
214
+ use_gpu=use_gpu,
215
+ model=model,
216
+ custom_model=custom_model,
217
+ diameter=diameter,
218
+ save_mask_as_png=save_mask_as_png,
219
+ )
220
+
221
+ # Remove single-dimensional entries from the shape of segmentation_masks
222
+ masks_whole_cell = masks_whole_cell.squeeze()
223
+ # Get the original dimensions of any one of the images
224
+ original_height, original_width = image_dict[
225
+ nuclei_channel
226
+ ].shape # or any other channel
227
+ # Resize the masks back to the original size
228
+ masks_whole_cell = cv2.resize(
229
+ masks_whole_cell,
230
+ (original_width, original_height),
231
+ interpolation=cv2.INTER_NEAREST,
232
+ )
233
+
234
+ # Remove single-dimensional entries from the shape of segmentation_masks
235
+ masks_nuclei = masks_nuclei.squeeze()
236
+ # Get the original dimensions of any one of the images
237
+ original_height, original_width = image_dict[
238
+ nuclei_channel
239
+ ].shape # or any other channel
240
+ # Resize the masks back to the original size
241
+ masks_nuclei = cv2.resize(
242
+ masks_nuclei,
243
+ (original_width, original_height),
244
+ interpolation=cv2.INTER_NEAREST,
245
+ )
246
+
247
+ # Create binary masks
248
+ binary_masks_nuclei = masks_nuclei > 0
249
+ binary_masks_whole_cell = masks_whole_cell > 0
250
+
251
+ # Subtract the binary nuclei mask from the binary whole cell mask
252
+ binary_masks_cytoplasm = binary_masks_whole_cell & ~binary_masks_nuclei
253
+
254
+ # Now, if you want to get a labeled mask for the cytoplasm, you can use a function like `label` from `scipy.ndimage`
255
+ from scipy.ndimage import label
256
+
257
+ masks_cytoplasm, num_labels = label(binary_masks_cytoplasm)
258
+
259
+ print("Quantifying features after segmentation!")
260
+ print("Quantifying features nuclei")
261
+ nuc = extract_features(
262
+ image_dict=image_dict, # image dictionary
263
+ segmentation_masks=masks_nuclei, # segmentation masks generated by cellpose
264
+ channels_to_quantify=channel_names, # list of channels to quantify (here: all channels)
265
+ output_file=pathlib.Path(output_dir)
266
+ / (
267
+ output_fname + "_" + seg_method + "_nuclei_result.csv"
268
+ ), # output path to store results as csv
269
+ size_cutoff=size_cutoff,
270
+ ) # size cutoff for segmentation masks (default = 0)
271
+ print("Quantifying features cytoplasm")
272
+ cyto = extract_features(
273
+ image_dict=image_dict, # image dictionary
274
+ segmentation_masks=masks_cytoplasm, # segmentation masks generated by cellpose
275
+ channels_to_quantify=channel_names, # list of channels to quantify (here: all channels)
276
+ output_file=pathlib.Path(output_dir)
277
+ / (
278
+ output_fname + "_" + seg_method + "_cytoplasm_result.csv"
279
+ ), # output path to store results as csv
280
+ size_cutoff=size_cutoff,
281
+ ) # size cutoff for segmentation masks (default = 0)
282
+
283
+ print("Quantifying features whole cell")
284
+ whole = extract_features(
285
+ image_dict=image_dict, # image dictionary
286
+ segmentation_masks=masks_whole_cell, # segmentation masks generated by cellpose
287
+ channels_to_quantify=channel_names, # list of channels to quantify (here: all channels)
288
+ output_file=pathlib.Path(output_dir)
289
+ / (
290
+ output_fname + "_" + seg_method + "_whole_cell_result.csv"
291
+ ), # output path to store results as csv
292
+ size_cutoff=size_cutoff,
293
+ ) # size cutoff for segmentation masks (default = 0)
294
+ print("Done!")
295
+
296
+ # remove
297
+ out = [
298
+ "x",
299
+ "y",
300
+ "eccentricity",
301
+ "perimeter",
302
+ "convex_area",
303
+ "area",
304
+ "axis_major_length",
305
+ "axis_minor_length",
306
+ "label",
307
+ ]
308
+
309
+ # keep metadata
310
+ whole_meta = whole[out]
311
+
312
+ # remove from nuc
313
+ nuc = nuc.drop(out, axis=1)
314
+ # add whole metadata to cyto
315
+ nuc_save = pd.concat([nuc, whole_meta], axis=1)
316
+ nuc_save.to_csv(
317
+ output_dir
318
+ + output_fname
319
+ + "_"
320
+ + seg_method
321
+ + "_nuclei_intensities_result.csv"
322
+ )
323
+ # remove from cyto
324
+ cyto = cyto.drop(out, axis=1)
325
+ # add whole metadata to cyto
326
+ cyto_save = pd.concat([cyto, whole_meta], axis=1)
327
+ cyto_save.to_csv(
328
+ output_dir
329
+ + output_fname
330
+ + "_"
331
+ + seg_method
332
+ + "_cytoplasm_intensities_result.csv"
333
+ )
334
+
335
+ whole.to_csv(
336
+ output_dir
337
+ + output_fname
338
+ + "_"
339
+ + seg_method
340
+ + "_whole_cell_intensities_result.csv"
341
+ )
342
+ whole = whole.drop(out, axis=1)
343
+
344
+ # add identifier to each column name
345
+ nuc.columns = [str(col) + "_nuc" for col in nuc.columns]
346
+ cyto.columns = [str(col) + "_cyto" for col in cyto.columns]
347
+ whole.columns = [str(col) + "_whole" for col in whole.columns]
348
+
349
+ # combine the dataframes and save as csv
350
+ result = pd.concat([nuc, cyto, whole, whole_meta], axis=1)
351
+ result = result.loc[:, ~result.columns.str.contains("Unnamed: 0")]
352
+ result.to_csv(
353
+ output_dir
354
+ + output_fname
355
+ + "_"
356
+ + seg_method
357
+ + "_segmentation_results_combined.csv"
358
+ )
359
+
360
+ return {
361
+ "img": img,
362
+ "masks": masks_whole_cell,
363
+ "image_dict": image_dict,
364
+ "masks_cytoplasm": masks_cytoplasm,
365
+ "masks_nuclei": masks_nuclei,
366
+ }
367
+
368
+ else:
369
+ if seg_method == "mesmer":
370
+ print("Segmenting with Mesmer!")
371
+ if membrane_channel_list is None:
372
+ masks = mesmer_segmentation(
373
+ nuclei_image=segmentation_image_dict[nuclei_channel],
374
+ membrane_image=None,
375
+ plot_predictions=plot_predictions, # plot segmentation results
376
+ compartment="nuclear",
377
+ model_path=model_path,
378
+ ) # segment whole cells or nuclei only
379
+ else:
380
+ masks = mesmer_segmentation(
381
+ nuclei_image=segmentation_image_dict[nuclei_channel],
382
+ membrane_image=segmentation_image_dict["segmentation_channel"],
383
+ plot_predictions=plot_predictions, # plot segmentation results
384
+ compartment=compartment,
385
+ model_path=model_path,
386
+ ) # segment whole cells or nuclei only
387
+ else:
388
+ print("Segmenting with Cellpose!")
389
+ if membrane_channel_list is None:
390
+ masks, flows, styles, input_image, rgb_channels = cellpose_segmentation(
391
+ image_dict=segmentation_image_dict,
392
+ output_dir=output_dir,
393
+ membrane_channel=None,
394
+ cytoplasm_channel=cytoplasm_channel_list,
395
+ nucleus_channel=nuclei_channel,
396
+ use_gpu=use_gpu,
397
+ model=model,
398
+ custom_model=custom_model,
399
+ diameter=diameter,
400
+ save_mask_as_png=save_mask_as_png,
401
+ )
402
+ else:
403
+ masks, flows, styles, input_image, rgb_channels = cellpose_segmentation(
404
+ image_dict=segmentation_image_dict,
405
+ output_dir=output_dir,
406
+ membrane_channel="segmentation_channel",
407
+ cytoplasm_channel=cytoplasm_channel_list,
408
+ nucleus_channel=nuclei_channel,
409
+ use_gpu=use_gpu,
410
+ model=model,
411
+ custom_model=custom_model,
412
+ diameter=diameter,
413
+ save_mask_as_png=save_mask_as_png,
414
+ )
415
+ # Remove single-dimensional entries from the shape of segmentation_masks
416
+ masks = masks.squeeze()
417
+ # Get the original dimensions of any one of the images
418
+ original_height, original_width = image_dict[
419
+ nuclei_channel
420
+ ].shape # or any other channel
421
+ # Resize the masks back to the original size
422
+ masks = cv2.resize(
423
+ masks, (original_width, original_height), interpolation=cv2.INTER_NEAREST
424
+ )
425
+ print("Quantifying features after segmentation!")
426
+ extract_features(
427
+ image_dict=image_dict, # image dictionary
428
+ segmentation_masks=masks, # segmentation masks generated by cellpose
429
+ channels_to_quantify=channel_names, # list of channels to quantify (here: all channels)
430
+ output_file=pathlib.Path(output_dir)
431
+ / (
432
+ output_fname + "_" + seg_method + "_result.csv"
433
+ ), # output path to store results as csv
434
+ size_cutoff=size_cutoff,
435
+ ) # size cutoff for segmentation masks (default = 0)
436
+ print("Done!")
437
+ return {"img": img, "masks": masks, "image_dict": image_dict}
438
+
439
+
440
+ def extract_features(
441
+ image_dict, segmentation_masks, channels_to_quantify, output_file, size_cutoff=0
442
+ ):
443
+ """
444
+ Extract features from the given image dictionary and segmentation masks.
445
+
446
+ Parameters
447
+ ----------
448
+ image_dict : dict
449
+ Dictionary containing image data. Keys are channel names, values are 2D numpy arrays.
450
+ segmentation_masks : ndarray
451
+ 2D numpy array containing segmentation masks.
452
+ channels_to_quantify : list
453
+ List of channel names to quantify.
454
+ output_file : str
455
+ Path to the output CSV file.
456
+ size_cutoff : int, optional
457
+ Minimum size of nucleus to consider. Nuclei smaller than this are ignored. Default is 0.
458
+
459
+ Returns
460
+ -------
461
+ None
462
+ The function doesn't return anything but writes the extracted features to a CSV file.
463
+
464
+ """
465
+ segmentation_masks = segmentation_masks.squeeze()
466
+
467
+ # Count pixels for each nucleus
468
+ _, counts = np.unique(segmentation_masks, return_counts=True)
469
+
470
+ # Identify nucleus IDs above the size cutoff, excluding background (ID 0)
471
+ nucleus_ids = np.where(counts > size_cutoff)[0][1:]
472
+
473
+ # Filter out small objects from segmentation masks
474
+ filterimg = np.where(
475
+ np.isin(segmentation_masks, nucleus_ids), segmentation_masks, 0
476
+ )
477
+
478
+ # Extract morphological features
479
+ props = regionprops_table(
480
+ filterimg,
481
+ properties=(
482
+ "centroid",
483
+ "eccentricity",
484
+ "perimeter",
485
+ "convex_area",
486
+ "area",
487
+ "axis_major_length",
488
+ "axis_minor_length",
489
+ "label",
490
+ ),
491
+ )
492
+ props_df = pd.DataFrame(props)
493
+ props_df.set_index(props_df["label"], inplace=True)
494
+
495
+ # Pre-allocate array for mean intensities
496
+ mean_intensities = np.empty((len(nucleus_ids), len(channels_to_quantify)))
497
+
498
+ # For each channel, compute mean intensities for all labels using vectorized operations
499
+ for idx, chan in enumerate(tqdm(channels_to_quantify, desc="Processing channels")):
500
+ chan_data = image_dict[chan]
501
+ labels_matrix = (
502
+ np.isin(segmentation_masks, nucleus_ids).astype(int) * segmentation_masks
503
+ )
504
+ sum_per_label = np.bincount(labels_matrix.ravel(), weights=chan_data.ravel())[
505
+ nucleus_ids
506
+ ]
507
+ count_per_label = np.bincount(labels_matrix.ravel())[nucleus_ids]
508
+ mean_intensities[:, idx] = sum_per_label / count_per_label
509
+
510
+ # Convert the array to a DataFrame
511
+ mean_df = pd.DataFrame(
512
+ mean_intensities, index=nucleus_ids, columns=channels_to_quantify
513
+ )
514
+
515
+ # Join with morphological features
516
+ markers = mean_df.join(props_df)
517
+
518
+ # rename column
519
+ markers.rename(columns={"centroid-0": "y"}, inplace=True)
520
+ markers.rename(columns={"centroid-1": "x"}, inplace=True)
521
+
522
+ # Export to CSV
523
+ markers.to_csv(output_file)
524
+
525
+ return markers
526
+
527
+
528
+ def cellpose_segmentation(
529
+ image_dict,
530
+ output_dir,
531
+ membrane_channel=None,
532
+ cytoplasm_channel=None,
533
+ nucleus_channel=None,
534
+ use_gpu=True,
535
+ model="cyto3",
536
+ custom_model=False,
537
+ diameter=None,
538
+ save_mask_as_png=False,
539
+ ):
540
+ """
541
+ Perform cell segmentation using CellPose.
542
+
543
+ Parameters
544
+ ----------
545
+ image_dict : dict
546
+ Dictionary containing image data. Keys are channel names, values are 2D numpy arrays.
547
+ output_dir : str
548
+ Directory where the output will be saved.
549
+ membrane_channel : str, optional
550
+ Name of the membrane channel. Default is None.
551
+ cytoplasm_channel : str, optional
552
+ Name of the cytoplasm channel. Default is None.
553
+ nucleus_channel : str
554
+ Name of the nucleus channel. Default is None.
555
+ use_gpu : bool, optional
556
+ Whether to use GPU for computation. Default is True.
557
+ model : str, optional
558
+ Model to use for segmentation. Default is "nuclei".
559
+ pretrained_model : bool, optional
560
+ Whether to use a pretrained model. Default is False.
561
+ diameter : float, optional
562
+ Diameter of cells. If None, it will be estimated automatically. Default is None. However, it is recommended to provide the diameter for better results.
563
+ save_mask_as_png : bool, optional
564
+ Whether to save the mask as a PNG file. Default is False.
565
+
566
+ Returns
567
+ -------
568
+ masks : ndarray
569
+ 2D numpy array containing segmentation masks.
570
+ flows : ndarray
571
+ 2D numpy array containing flows.
572
+ styles : ndarray
573
+ 2D numpy array containing styles.
574
+ input_image : ndarray
575
+ 2D numpy array containing the input image.
576
+ rgb_channels : list
577
+ List of RGB channels used for segmentation.
578
+
579
+ """
580
+ # Default values for rgb_channels
581
+ rgb_channels = [0, 0]
582
+ grey_channel = None
583
+
584
+ # Check nucleus channel
585
+ if not nucleus_channel:
586
+ print("Please select a nucleus channel!")
587
+ return
588
+
589
+ # Channel selection logic
590
+ if cytoplasm_channel:
591
+ if membrane_channel:
592
+ print(
593
+ "CellPose expects only two channels as input. Selecting nucleus channel and cytoplasm channel. If you want to use nucleus and membrane instead set cytoplasm_channel to None."
594
+ )
595
+ else:
596
+ print("Selecting nucleus and cytoplasm channel for segmentation.")
597
+ rgb_channels = [2, 3]
598
+ elif membrane_channel:
599
+ print("Selecting nucleus and membrane channel for segmentation.")
600
+ rgb_channels = [1, 3]
601
+
602
+ # Run CellPose
603
+ if membrane_channel is None and cytoplasm_channel is None:
604
+ input_image = RGB_for_segmentation(
605
+ membrane_channel, cytoplasm_channel, nucleus_channel, image_dict
606
+ )
607
+ # extract only the blue channel
608
+ final_input = input_image[:, :, 2]
609
+
610
+ else:
611
+ input_image = RGB_for_segmentation(
612
+ membrane_channel, cytoplasm_channel, nucleus_channel, image_dict
613
+ )
614
+ final_input = input_image.copy()
615
+
616
+ masks, flows, styles = run_cellpose(
617
+ final_input,
618
+ output_dir=output_dir,
619
+ use_gpu=use_gpu,
620
+ model=model,
621
+ custom_model=custom_model,
622
+ diameter=diameter,
623
+ rgb_channels=rgb_channels,
624
+ save_mask_as_png=save_mask_as_png,
625
+ )
626
+
627
+ return masks, flows, styles, input_image, rgb_channels
628
+
629
+
630
+ def RGB_for_segmentation(
631
+ membrane_channel, cytoplasm_channel, nucleus_channel, image_dict
632
+ ):
633
+ """
634
+ Prepare an RGB image for segmentation from the given channels.
635
+
636
+ Parameters
637
+ ----------
638
+ membrane_channel : str
639
+ Name of the membrane channel.
640
+ cytoplasm_channel : str
641
+ Name of the cytoplasm channel.
642
+ nucleus_channel : str
643
+ Name of the nucleus channel.
644
+ image_dict : dict
645
+ Dictionary containing image data. Keys are channel names, values are 2D numpy arrays.
646
+
647
+ Returns
648
+ -------
649
+ rgb_image : ndarray or None
650
+ 3D numpy array containing the RGB image for segmentation. If no valid channels are found, returns None.
651
+
652
+ """
653
+ # Initialize channels with None
654
+ red_channel, green_channel, blue_channel = None, None, None
655
+
656
+ # Check for membrane_channel
657
+ if membrane_channel in image_dict:
658
+ red_channel = image_dict[membrane_channel]
659
+
660
+ # Check for cytoplasm_channel
661
+ if cytoplasm_channel in image_dict:
662
+ green_channel = image_dict[cytoplasm_channel]
663
+
664
+ # Check for nucleus_channel
665
+ if nucleus_channel in image_dict:
666
+ blue_channel = image_dict[nucleus_channel]
667
+
668
+ # If any of the channels is None, create an empty channel with the same shape as the others
669
+ shape = None
670
+ for channel in [red_channel, green_channel, blue_channel]:
671
+ if channel is not None:
672
+ shape = channel.shape
673
+ break
674
+
675
+ if red_channel is None and shape:
676
+ red_channel = np.zeros(shape, dtype=np.uint8)
677
+
678
+ if green_channel is None and shape:
679
+ green_channel = np.zeros(shape, dtype=np.uint8)
680
+
681
+ if blue_channel is None and shape:
682
+ blue_channel = np.zeros(shape, dtype=np.uint8)
683
+
684
+ # Stack the channels to create an RGB image
685
+ if shape: # Only if we found a valid shape
686
+ rgb_image = np.dstack((red_channel, green_channel, blue_channel))
687
+ return rgb_image
688
+ else:
689
+ # Handle the case where no valid channels are found
690
+ return None
691
+
692
+
693
+ def run_cellpose(
694
+ image,
695
+ output_dir,
696
+ use_gpu=True,
697
+ model="nuclei",
698
+ custom_model=False,
699
+ diameter=None,
700
+ rgb_channels=[0, 0],
701
+ save_mask_as_png=False,
702
+ ):
703
+ """
704
+ Run CellPose model on the given image.
705
+
706
+ Parameters
707
+ ----------
708
+ image : ndarray
709
+ 2D or 3D numpy array containing the image data.
710
+ output_dir : str
711
+ Directory where the output will be saved.
712
+ use_gpu : bool, optional
713
+ Whether to use GPU for computation. Default is True.
714
+ model : str, optional
715
+ Model to use for segmentation. Default is "nuclei".
716
+ pretrained_model : bool, optional
717
+ Whether to use a pretrained model. Default is False.
718
+ diameter : float, optional
719
+ Diameter of cells. If None, it will be estimated automatically. Default is None.
720
+ rgb_channels : list, optional
721
+ List of RGB channels used for segmentation. Default is [0, 0].
722
+ save_mask_as_png : bool, optional
723
+ Whether to save the mask as a PNG file. Default is False.
724
+
725
+ Returns
726
+ -------
727
+ masks : ndarray
728
+ 2D numpy array containing segmentation masks.
729
+ flows : ndarray
730
+ 2D numpy array containing flows.
731
+ styles : ndarray
732
+ 2D numpy array containing styles.
733
+
734
+ """
735
+ # IF ALL YOUR IMAGES ARE THE SAME TYPE, you can give a list with 2 elements
736
+ # channels = [0,0] # IF YOU HAVE GRAYSCALE
737
+ # channels = [2,3] # IF YOU HAVE G=cytoplasm and B=nucleus
738
+ # channels = [2,1] # IF YOU HAVE G=cytoplasm and R=nucleus
739
+
740
+ if custom_model == True:
741
+ model_to_use = models.CellposeModel(model_type=model, gpu=use_gpu)
742
+ else:
743
+ model_to_use = models.Cellpose(
744
+ model_type=model,
745
+ gpu=use_gpu,
746
+ )
747
+ masks, flows, styles, diams = model_to_use.eval(
748
+ image, diameter=diameter, channels=rgb_channels
749
+ )
750
+ print("diameter set to: " + str(diams))
751
+
752
+ if save_mask_as_png == True:
753
+ filename = output_dir + "/segmentation.png"
754
+ io.save_to_png(image, masks, flows, filename)
755
+
756
+ return masks, flows, styles
757
+
758
+
759
+ def load_mesmer_model(path):
760
+ """
761
+ Load the Mesmer model from the given path. If the model is not found, it is downloaded.
762
+
763
+ Parameters
764
+ ----------
765
+ path : str
766
+ Path where the Mesmer model is located or will be downloaded.
767
+
768
+ Returns
769
+ -------
770
+ mesmer_pretrained_model : tensorflow.python.keras.engine.training.Model
771
+ The loaded Mesmer model.
772
+
773
+ """
774
+ # check if folder Mesmer_model exist
775
+ if not os.path.exists(os.path.join(path, "Mesmer_model")):
776
+ os.makedirs(os.path.join(path, "Mesmer_model"))
777
+
778
+ print("downloading Mesmer model")
779
+
780
+ # download model from https://deepcell-data.s3-us-west-1.amazonaws.com/saved-models/MultiplexSegmentation-9.tar.gz
781
+ url = "https://deepcell-data.s3-us-west-1.amazonaws.com/saved-models/MultiplexSegmentation-9.tar.gz"
782
+ response = requests.get(url)
783
+
784
+ # Ensure the download was successful
785
+ response.raise_for_status()
786
+
787
+ # Write the content of the response to a file in the 'Mesmer_model' directory
788
+ with open(
789
+ os.path.join(path, "Mesmer_model/MultiplexSegmentation.tar.gz"), "wb"
790
+ ) as f:
791
+ f.write(response.content)
792
+
793
+ # unpack tar file
794
+ shutil.unpack_archive(
795
+ os.path.join(path, "Mesmer_model/MultiplexSegmentation.tar.gz"),
796
+ os.path.join(path, "Mesmer_model/"),
797
+ )
798
+
799
+ # delete the .tar.gz file
800
+ os.remove(os.path.join(path, "Mesmer_model/MultiplexSegmentation.tar.gz"))
801
+
802
+ # move content of folder MultiplexSegmentation to Mesmer_model
803
+ # shutil.move(os.path.join(path, 'Mesmer_model/MultiplexSegmentation'), os.path.join(path, 'Mesmer_model/'))
804
+
805
+ # remove empty folder MultiplexSegmentation
806
+ # os.rmdir(os.path.join(path, 'Mesmer_model/MultiplexSegmentation'))
807
+
808
+ print("Mesmer model downloaded and unpacked")
809
+
810
+ model_path = os.path.join(path, "Mesmer_model/MultiplexSegmentation")
811
+
812
+ mesmer_pretrained_model = load_model(model_path, compile=False)
813
+
814
+ return mesmer_pretrained_model
815
+
816
+
817
+ def mesmer_segmentation(
818
+ nuclei_image,
819
+ membrane_image,
820
+ image_mpp=0.5,
821
+ plot_predictions=True,
822
+ compartment="whole-cell", # or 'nuclear'
823
+ model_path="./models",
824
+ ):
825
+ """
826
+ Perform segmentation on the given images using the Mesmer model.
827
+
828
+ Parameters
829
+ ----------
830
+ nuclei_image : ndarray
831
+ 2D numpy array containing the nuclei image data.
832
+ membrane_image : ndarray
833
+ 2D numpy array containing the membrane image data.
834
+ image_mpp : float, optional
835
+ Microns per pixel for the images. Default is 0.5.
836
+ plot_predictions : bool, optional
837
+ Whether to plot the predictions. Default is True.
838
+ compartment : str, optional
839
+ Compartment to segment. Can be 'whole-cell' or 'nuclear'. Default is 'whole-cell'.
840
+ model_path : str, optional
841
+ Path where the Mesmer model is located. Default is './models'.
842
+
843
+ Returns
844
+ -------
845
+ segmented_image : ndarray
846
+ 3D numpy array containing the segmentation results.
847
+
848
+ """
849
+ pathlib.Path(model_path).mkdir(parents=True, exist_ok=True)
850
+ mesmer_pretrained_model = load_mesmer_model(model_path)
851
+
852
+ # Initialize Mesmer application
853
+ app = Mesmer(model=mesmer_pretrained_model)
854
+
855
+ # Create a combined image stack
856
+ # Assumes nuclei_image and membrane_image are numpy arrays of the same shape
857
+ if membrane_image is None:
858
+ # generate empty membrane image
859
+ print("No membrane image provided. Nuclear segmentation only.")
860
+ membrane_image = np.zeros_like(nuclei_image)
861
+ combined_image = np.stack([nuclei_image, membrane_image], axis=-1)
862
+ else:
863
+ combined_image = np.stack([nuclei_image, membrane_image], axis=-1)
864
+
865
+ # Add an extra dimension to make it compatible with Mesmer's input requirements
866
+ # Changes shape from (height, width, channels) to (1, height, width, channels)
867
+ combined_image = np.expand_dims(combined_image, axis=0)
868
+
869
+ # Run the Mesmer model
870
+ segmented_image = app.predict(
871
+ combined_image, image_mpp=image_mpp, compartment=compartment
872
+ )
873
+
874
+ if plot_predictions == True:
875
+ # create rgb overlay of image data for visualization
876
+ rgb_images = create_rgb_image(combined_image, channel_colors=["green", "blue"])
877
+ # create overlay of segmentation results
878
+ overlay_data = make_outline_overlay(
879
+ rgb_data=rgb_images, predictions=segmented_image
880
+ )
881
+
882
+ # select index for displaying
883
+ idx = 0
884
+
885
+ # plot the data
886
+ # TODO: plotting and calculating should probably not be in the same figure
887
+ fig, ax = plt.subplots(1, 2, figsize=(15, 15))
888
+ ax[0].imshow(rgb_images[idx, ...])
889
+ ax[1].imshow(overlay_data[idx, ...])
890
+ ax[0].set_title("Raw data")
891
+ ax[1].set_title("Predictions")
892
+ plt.show()
893
+
894
+ # The output will be a numpy array with the segmentation results
895
+ return segmented_image