Skip to content

Commit d4857f5

Browse files
adding docs for restore
1 parent e453d1b commit d4857f5

19 files changed

+1210
-1070
lines changed

cellpose/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def main():
166166
invert=args.invert, batch_size=args.batch_size,
167167
interp=(not args.no_interp), normalize=(not args.no_norm),
168168
channel_axis=args.channel_axis, z_axis=args.z_axis,
169-
anisotropy=args.anisotropy)
169+
anisotropy=args.anisotropy, niter=args.niter)
170170
masks, flows = out[:2]
171171
if len(out) > 3:
172172
diams = out[-1]

cellpose/cli.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,9 @@ def get_arg_parser():
105105
algorithm_args.add_argument(
106106
"--cellprob_threshold", default=0, type=float,
107107
help="cellprob threshold, default is 0, decrease to find more and larger masks")
108+
algorithm_args.add_argument(
109+
"--niter", default=0, type=int,
110+
help="niter, number of iterations for dynamics for mask creation, default of 0 means it is proportional to diameter, set to a larger number like 2000 for very long ROIs")
108111

109112
algorithm_args.add_argument("--anisotropy", required=False, default=1.0, type=float,
110113
help="anisotropy of volume in 3D")

cellpose/io.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -423,12 +423,10 @@ def load_images_labels(tdir, mask_filter="_masks", image_filter=None,
423423
k = 0
424424
for n in range(nimg):
425425
if os.path.isfile(label_names[n]) or os.path.isfile(flow_names[0]):
426-
print(image_names[n])
427426
image = imread(image_names[n])
428427
if label_names is not None:
429428
label = imread(label_names[n])
430429
if flow_names is not None:
431-
print(flow_names[n])
432430
flow = imread(flow_names[n])
433431
if flow.shape[0] < 4:
434432
label = np.concatenate((label[np.newaxis, :, :], flow), axis=0)

cellpose/models.py

Lines changed: 32 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ class Cellpose():
9090
device (torch device, optional): Device used for model running / training. Overrides gpu input. Recommended if you want to use a specific GPU (e.g. torch.device("cuda:1")). Defaults to None.
9191
9292
Attributes:
93-
torch (bool): Flag indicating if torch is available.
9493
device (torch device): Device used for model running / training.
9594
gpu (bool): Flag indicating if GPU is used.
9695
diam_mean (float): Mean diameter for cytoplasm model.
@@ -202,7 +201,6 @@ class CellposeModel():
202201
Class representing a Cellpose model.
203202
204203
Attributes:
205-
torch (bool): Whether or not the torch library is available.
206204
diam_mean (float): Mean "diameter" value for the model.
207205
builtin (bool): Whether the model is a built-in model or not.
208206
device (torch device): Device used for model running / training.
@@ -357,9 +355,10 @@ def eval(self, x, batch_size=8, resample=True, channels=None, channel_axis=None,
357355
progress (QProgressBar, optional): pyqt progress bar. Defaults to None.
358356
359357
Returns:
360-
masks (list, np.ndarray): labelled image(s), where 0=no masks; 1,2,...=mask labels
361-
flows (list): list of lists: flows[k][0] = XY flow in HSV 0-255; flows[k][1] = XY(Z) flows at each pixel; flows[k][2] = cell probability (if > cellprob_threshold, pixel used for dynamics); flows[k][3] = final pixel locations after Euler integration
362-
styles (list, np.ndarray): style vector summarizing each image of size 256.
358+
A tuple containing:
359+
- masks (list, np.ndarray): labelled image(s), where 0=no masks; 1,2,...=mask labels
360+
- flows (list): list of lists: flows[k][0] = XY flow in HSV 0-255; flows[k][1] = XY(Z) flows at each pixel; flows[k][2] = cell probability (if > cellprob_threshold, pixel used for dynamics); flows[k][3] = final pixel locations after Euler integration
361+
- styles (list, np.ndarray): style vector summarizing each image of size 256.
363362
364363
"""
365364
if isinstance(x, list) or x.squeeze().ndim == 5:
@@ -501,7 +500,7 @@ def _run_cp(self, x, compute_masks=True, normalize=True, invert=False, niter=Non
501500
if compute_masks:
502501
tic = time.time()
503502
niter0 = 200 if (do_3D and not resample) else (1 / rescale * 200)
504-
niter = niter0 if niter is None else niter
503+
niter = niter0 if niter is None or niter==0 else niter
505504
if do_3D:
506505
masks, p = dynamics.resize_and_compute_masks(
507506
dP, cellprob, niter=niter, cellprob_threshold=cellprob_threshold,
@@ -552,17 +551,6 @@ def _run_cp(self, x, compute_masks=True, normalize=True, invert=False, niter=Non
552551
masks, p = np.zeros(0), np.zeros(0) #pass back zeros if not compute_masks
553552
return masks, styles, dP, cellprob, p
554553

555-
def loss_fn(self, lbl, y):
556-
""" loss function between true labels lbl and prediction y """
557-
veci = 5. * self._to_device(lbl[:, 1:])
558-
lbl = self._to_device(lbl[:, 0] > .5).float()
559-
loss = self.criterion(y[:, :2], veci)
560-
loss /= 2.
561-
loss2 = self.criterion2(y[:, 2], lbl)
562-
loss = loss + loss2
563-
return loss
564-
565-
566554
class SizeModel():
567555
"""
568556
Linear regression model for determining the size of objects in image
@@ -612,50 +600,46 @@ def __init__(self, cp_model, device=None, pretrained_size=None, **kwargs):
612600
raise ValueError(error_message)
613601

614602
def eval(self, x, channels=None, channel_axis=None, normalize=True, invert=False,
615-
augment=False, tile=True, batch_size=8, progress=None, interp=True):
603+
augment=False, tile=True, batch_size=8, progress=None):
616604
"""Use images x to produce style or use style input to predict size of objects in image.
617605
618606
Object size estimation is done in two steps:
619607
1. Use a linear regression model to predict size from style in image.
620608
2. Resize image to predicted size and run CellposeModel to get output masks.
621609
Take the median object size of the predicted masks as the final predicted size.
622610
623-
Parameters:
624-
x: list or array of images
625-
Can be a list of 2D/3D images or an array of 2D/3D images.
626-
627-
channels: list (optional, default None)
628-
List of channels, either of length 2 or of length number of images by 2.
629-
The first element of the list is the channel to segment (0=grayscale, 1=red, 2=green, 3=blue).
630-
The second element of the list is the optional nuclear channel (0=none, 1=red, 2=green, 3=blue).
611+
Args:
612+
x (list, np.ndarry): can be list of 2D/3D/4D images, or array of 2D/3D/4D images
613+
channels (list, optional): list of channels, either of length 2 or of length number of images by 2.
614+
First element of list is the channel to segment (0=grayscale, 1=red, 2=green, 3=blue).
615+
Second element of list is the optional nuclear channel (0=none, 1=red, 2=green, 3=blue).
631616
For instance, to segment grayscale images, input [0,0]. To segment images with cells
632617
in green and nuclei in blue, input [2,3]. To segment one grayscale image and one
633618
image with cells in green and nuclei in blue, input [[0,0], [2,3]].
619+
Defaults to None.
620+
channel_axis (int, optional): channel axis in element of list x, or of np.ndarray x.
621+
if None, channels dimension is attempted to be automatically determined. Defaults to None.
622+
normalize (bool, optional): if True, normalize data so 0.0=1st percentile and 1.0=99th percentile of image intensities in each channel;
623+
can also pass dictionary of parameters (all keys are optional, default values shown):
624+
- "lowhigh"=None : pass in normalization values for 0.0 and 1.0 as list [low, high] (if not None, all following parameters ignored)
625+
- "sharpen"=0 ; sharpen image with high pass filter, recommended to be 1/4-1/8 diameter of cells in pixels
626+
- "normalize"=True ; run normalization (if False, all following parameters ignored)
627+
- "percentile"=None : pass in percentiles to use as list [perc_low, perc_high]
628+
- "tile_norm"=0 ; compute normalization in tiles across image to brighten dark areas, to turn on set to window size in pixels (e.g. 100)
629+
- "norm3D"=False ; compute normalization across entire z-stack rather than plane-by-plane in stitching mode.
630+
Defaults to True.
631+
invert (bool, optional): Invert image pixel intensity before running network (if True, image is also normalized). Defaults to False.
632+
augment (bool, optional): tiles image with overlapping tiles and flips overlapped regions to augment. Defaults to False.
633+
tile (bool, optional): tiles image to ensure GPU/CPU memory usage limited (recommended). Defaults to True.
634+
batch_size (int, optional): number of 224x224 patches to run simultaneously on the GPU
635+
(can make smaller or bigger depending on GPU memory usage). Defaults to 8.
636+
progress (QProgressBar, optional): pyqt progress bar. Defaults to None.
634637
635-
channel_axis: int (optional, default None)
636-
If None, the channels dimension is attempted to be automatically determined.
637-
638-
normalize: bool (default, True)
639-
Normalize data so 0.0=1st percentile and 1.0=99th percentile of image intensities in each channel.
640-
641-
invert: bool (optional, default False)
642-
Invert image pixel intensity before running the network.
643-
644-
augment: bool (optional, default False)
645-
Tile the image with overlapping tiles and flips overlapped regions to augment.
646-
647-
tile: bool (optional, default True)
648-
Tile the image to ensure GPU/CPU memory usage is limited (recommended).
649-
650-
progress: pyqt progress bar (optional, default None)
651-
Return progress bar status to GUI.
652638
653639
Returns:
654-
diam: array, float
655-
Final estimated diameters from images x or styles style after running both steps.
656-
657-
diam_style: array, float
658-
Estimated diameters from style alone.
640+
A tuple containing:
641+
- diam (np.ndarray): Final estimated diameters from images x or styles style after running both steps.
642+
- diam_style (np.ndarray): Estimated diameters from style alone.
659643
"""
660644

661645
if isinstance(x, list):

cellpose/train.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,8 @@ def train_seg(net, train_data=None, train_labels=None, train_files=None,
359359
(train_data, train_labels, train_files, train_labels_files, train_probs, diam_train,
360360
test_data, test_labels, test_files, test_labels_files, test_probs, diam_test) = out
361361

362+
net.diam_labels.data = torch.Tensor([diam_train.mean()]).to(device)
363+
362364
nimg = len(train_data) if train_data is not None else len(train_files)
363365
nimg_test = len(test_data) if test_data is not None else None
364366
nimg_test = len(test_files) if test_files is not None else nimg_test

cellpose/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,11 @@ def outlines_list(masks, multiprocessing_threshold=1000, multiprocessing=None):
226226
- This function is a wrapper for outlines_list_single and outlines_list_multi.
227227
- Multiprocessing is disabled for Windows.
228228
"""
229-
# default to use multiprocessing if few_masks, but allow user to override
229+
# default to use multiprocessing if not few_masks, but allow user to override
230230
if multiprocessing is None:
231231
few_masks = np.max(masks) < multiprocessing_threshold
232-
multiprocessing = few_masks
233-
232+
multiprocessing = not few_masks
233+
234234
# disable multiprocessing for Windows
235235
if os.name == "nt":
236236
if multiprocessing:

docs/api.rst

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,32 @@ CellposeModel
1515
.. autoclass:: cellpose.models.CellposeModel
1616
:members:
1717

18+
CellposeDenoiseModel
19+
~~~~~~~~~~~~~~~~~
20+
21+
.. autoclass:: cellpose.denoise.CellposeDenoiseModel
22+
:members:
23+
24+
25+
DenoiseModel
26+
~~~~~~~~~~~~~~~~~
27+
28+
.. autoclass:: cellpose.denoise.DenoiseModel
29+
:members:
30+
1831
SizeModel
1932
~~~~~~~~~~~~~~~~~
2033

2134
.. autoclass:: cellpose.models.SizeModel
2235
:members:
2336

37+
Training
38+
~~~~~~~~~~~~~~~~~~
39+
40+
.. automodule:: cellpose.train
41+
:members:
42+
43+
2444
Metrics
2545
~~~~~~~~~~~~~~~~~~
2646

docs/index.rst

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,19 @@ can install it as ``pip install cellpose[gui]``.
1313
You can try it out without installing at `cellpose.org`_.
1414
Also check out these resources:
1515

16-
Cellpose 2.0
16+
Cellpose3: one-click image restoration for improved cellular segmentation
17+
18+
- `paper <https://www.biorxiv.org/content/10.1101/2024.02.10.579780v1>`_ on biorxiv
19+
- `thread <https://neuromatch.social/@computingnature/111932247922392030>`_
20+
21+
Cellpose 2.0: how to train your own model
1722

1823
- `paper <https://www.biorxiv.org/content/10.1101/2022.04.01.486764v1>`_ on biorxiv
1924
- `talk <https://www.youtube.com/watch?v=3ydtAhfq6H0>`_
2025
- twitter `thread <https://twitter.com/marius10p/status/1511415409047650307?s=20&t=umTVIG1CFKIWHYMrQqFKyQ>`_
2126
- human-in-the-loop training protocol `video <https://youtu.be/3Y1VKcxjNy4>`_
2227

23-
Cellpose 1.0
28+
Cellpose: a generalist algorithm for cellular segmentation
2429

2530
- `paper <https://www.biorxiv.org/content/10.1101/2020.02.02.931238v1>`_ on biorxiv (see figure 1 below) and in `nature methods <https://t.co/kBMXmPp3Yn?amp=1>`_
2631
- twitter `thread <https://twitter.com/computingnature/status/1224477812763119617>`_
@@ -46,6 +51,7 @@ Cellpose 1.0
4651
settings
4752
outputs
4853
models
54+
restore
4955
train
5056
openvino
5157
faq

docs/installation.rst

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,17 +107,19 @@ Dependencies
107107
~~~~~~~~~~~~~~~~~~~~~~
108108

109109
cellpose relies on the following excellent packages (which are
110-
automatically installed with conda/pip if missing):
110+
automatically installed with pip if missing):
111111

112112
- `pytorch`_
113113
- `pyqtgraph`_
114-
- `PyQt5`_
114+
- `PyQt5`_ or pyside or PyQt6
115115
- `numpy`_ (>=1.16.0)
116116
- `numba`_
117117
- `scipy`_
118-
- `scikit-image`_
118+
- `tifffile`_
119119
- `natsort`_
120-
- `matplotlib`_
120+
- `fastremap`_
121+
- `roifile`_
122+
- `superqt`_
121123

122124
.. _Anaconda: https://www.anaconda.com/download/
123125
.. _environment.yml: https://github.com/MouseLand/cellpose/blob/master/environment.yml?raw=true
@@ -129,6 +131,8 @@ automatically installed with conda/pip if missing):
129131
.. _numpy: http://www.numpy.org/
130132
.. _numba: http://numba.pydata.org/numba-doc/latest/user/5minguide.html
131133
.. _scipy: https://www.scipy.org/
132-
.. _scikit-image: https://scikit-image.org/
134+
.. _tifffile: https://pypi.org/project/tifffile/
133135
.. _natsort: https://natsort.readthedocs.io/en/master/
134-
.. _matplotlib: https://matplotlib.org/
136+
.. _fastremap: https://github.com/seung-lab/fastremap
137+
.. _roifile: https://github.com/cgohlke/roifile
138+
.. _superqt: https://github.com/pyapp-kit/superqt

0 commit comments

Comments
 (0)