Skip to content

Commit

Permalink
fix #132 #151, modify jupyter notebook for #152 to show example
Browse files Browse the repository at this point in the history
  • Loading branch information
carsen-stringer committed Nov 24, 2020
1 parent d6cd00f commit a52a2ce
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 233 deletions.
88 changes: 42 additions & 46 deletions cellpose/__main__.py
Expand Up @@ -2,6 +2,7 @@
import subprocess
import numpy as np
from natsort import natsorted
from tqdm import tqdm

from . import utils, models, io

Expand Down Expand Up @@ -74,7 +75,6 @@ def main():
parser.add_argument('--concatenation', required=False,
default=0, type=int, help='concatenate downsampled layers with upsampled layers (off by default which means they are added)')


args = parser.parse_args()

if args.check_mkl:
Expand Down Expand Up @@ -108,8 +108,6 @@ def main():
else:
imf = None



if args.use_gpu:
use_gpu = models.use_gpu()
if use_gpu:
Expand All @@ -129,55 +127,53 @@ def main():

image_names = io.get_image_files(args.dir, args.mask_filter, imf=imf)
nimg = len(image_names)
images = [io.imread(image_names[n]) for n in range(nimg)]

if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei':
model = models.Cellpose(device=device, model_type=args.pretrained_model)

if args.diameter==0:
if args.diameter==0:
if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei':
diameter = None
print('>>>> estimating diameter for each image')
else:
diameter = args.diameter
print('>>>> using diameter %0.2f for all images'%diameter)

cstr0 = ['GRAY', 'RED', 'GREEN', 'BLUE']
cstr1 = ['NONE', 'RED', 'GREEN', 'BLUE']
print('running cellpose on %d images using chan_to_seg %s and chan (opt) %s'%
(nimg, cstr0[channels[0]], cstr1[channels[1]]))

masks, flows, _, diams = model.eval(images, channels=channels, diameter=diameter,
do_3D=args.do_3D, net_avg=(not args.fast_mode),
augment=False,
resample=args.resample,
flow_threshold=args.flow_threshold,
cellprob_threshold=args.cellprob_threshold,
batch_size=args.batch_size)

else:
if args.all_channels:
channels = None
model = models.CellposeModel(device=device, pretrained_model=cpmodel_path)
if args.diameter==0:
print('>>>> using user-specified model, no auto-diameter estimation available')
diameter = model.diam_mean
else:
diameter = args.diameter
print('>>>> using diameter %0.2f for all images'%diameter)

cstr0 = ['GRAY', 'RED', 'GREEN', 'BLUE']
cstr1 = ['NONE', 'RED', 'GREEN', 'BLUE']
print('>>>> running cellpose on %d images using chan_to_seg %s and chan (opt) %s'%
(nimg, cstr0[channels[0]], cstr1[channels[1]]))

for image_name in tqdm(image_names):
image = io.imread(image_name)

if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei':
model = models.Cellpose(device=device, model_type=args.pretrained_model)
masks, flows, _, diams = model.eval(image, channels=channels, diameter=diameter,
do_3D=args.do_3D, net_avg=(not args.fast_mode),
augment=False,
resample=args.resample,
flow_threshold=args.flow_threshold,
cellprob_threshold=args.cellprob_threshold,
batch_size=args.batch_size)

else:
diameter = args.diameter
rescale = model.diam_mean / diameter
masks, flows, _ = model.eval(images, channels=channels, rescale=rescale,
do_3D=args.do_3D,
augment=False,
resample=args.resample,
flow_threshold=args.flow_threshold,
cellprob_threshold=args.cellprob_threshold,
batch_size=args.batch_size)
diams = diameter * np.ones(len(images))

print('>>>> saving results')
if not args.no_npy:
io.masks_flows_to_seg(images, masks, flows, diams, image_names, channels)
if args.save_png or args.save_tif:
io.save_masks(images, masks, flows, image_names, png=args.save_png, tif=args.save_tif)
if args.all_channels:
channels = None
model = models.CellposeModel(device=device, pretrained_model=cpmodel_path)

rescale = model.diam_mean / diameter
masks, flows, _ = model.eval(image, channels=channels, rescale=rescale,
do_3D=args.do_3D,
augment=False,
resample=args.resample,
flow_threshold=args.flow_threshold,
cellprob_threshold=args.cellprob_threshold,
batch_size=args.batch_size)

if not args.no_npy:
io.masks_flows_to_seg(image, masks, flows, diams, image_name, channels)
if args.save_png or args.save_tif:
io.save_masks(image, masks, flows, image_name, png=args.save_png, tif=args.save_tif)
print('>>>> completed in %0.3f sec'%(time.time()-tic))
else:
if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei':
Expand Down
39 changes: 22 additions & 17 deletions cellpose/io.py
Expand Up @@ -209,8 +209,8 @@ def masks_flows_to_seg(images, masks, flows, diams, file_names, channels=None):
base = os.path.splitext(file_names)[0]
if masks.ndim==3:
np.save(base+ '_seg.npy',
{'outlines': outlines.astype(np.uint16),
'masks': masks.astype(np.uint16),
{'outlines': outlines.astype(np.uint16) if outlines.max()<2**16-1 else outlines.astype(np.uint32),
'masks': masks.astype(np.uint16) if outlines.max()<2**16-1 else masks.astype(np.uint32),
'chan_choose': channels,
'img': images,
'ismanual': np.zeros(masks.max(), np.bool),
Expand All @@ -221,13 +221,13 @@ def masks_flows_to_seg(images, masks, flows, diams, file_names, channels=None):
if images.shape[0]<8:
np.transpose(images, (1,2,0))
np.save(base+ '_seg.npy',
{'outlines': outlines.astype(np.uint16),
'masks': masks.astype(np.uint16),
'chan_choose': channels,
'ismanual': np.zeros(masks.max(), np.bool),
'filename': file_names,
'flows': flowi,
'est_diam': diams})
{'outlines': outlines.astype(np.uint16) if outlines.max()<2**16-1 else outlines.astype(np.uint32),
'masks': masks.astype(np.uint16) if masks.max()<2**16-1 else masks.astype(np.uint32),
'chan_choose': channels,
'ismanual': np.zeros(masks.max(), np.bool),
'filename': file_names,
'flows': flowi,
'est_diam': diams})

def save_to_png(images, masks, flows, file_names):
""" deprecated (runs io.save_masks with png=True)
Expand Down Expand Up @@ -272,21 +272,24 @@ def save_masks(images, masks, flows, file_names, png=True, tif=False):

if masks.ndim > 2 and not tif:
raise ValueError('cannot save 3D outputs as PNG, use tif option instead')
print(masks.shape)
base = os.path.splitext(file_names)[0]
exts = []
if masks.ndim > 2:
if masks.ndim > 2 or masks.max()>2**16-1:
png = False
tif = True
if png:
exts.append('.png')
if tif:
exts.append('.tif')

# convert to uint16 if possible so can save as PNG if needed
masks = masks.astype(np.uint16) if masks.max()<2**16-1 else masks.astype(np.uint32)

# save masks
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for ext in exts:
imsave(base + '_cp_masks' + ext, masks.astype(np.uint16))
imsave(base + '_cp_masks' + ext, masks)

if png and MATPLOTLIB and not min(images.shape) > 3:
img = images.copy()
Expand Down Expand Up @@ -553,7 +556,7 @@ def _load_seg(parent, filename=None, image=None, image_file=None):
parent.cellpix = dat['masks']
parent.outpix = dat['outlines']
parent.cellcolors.extend(colors)
parent.ncells = np.uint16(parent.cellpix.max())
parent.ncells = parent.cellpix.max()
parent.draw_masks()
if 'est_diam' in dat:
parent.Diameter.setText('%0.1f'%dat['est_diam'])
Expand Down Expand Up @@ -642,13 +645,15 @@ def _masks_to_gui(parent, masks, outlines=None):
shape = masks.shape
_, masks = np.unique(masks, return_inverse=True)
masks = np.reshape(masks, shape)
parent.cellpix = masks.astype(np.uint16)
masks = masks.astype(np.uint16) if masks.max()<2**16-1 else masks.astype(np.uint32)
parent.cellpix = masks

# get outlines
if outlines is None:
parent.outpix = np.zeros(masks.shape, np.uint16)
parent.outpix = np.zeros_like(masks)
for z in range(parent.NZ):
outlines = utils.masks_to_outlines(masks[z])
parent.outpix[z] = ((outlines * masks[z])).astype(np.uint16)
parent.outpix[z] = outlines * masks[z]
if z%50==0:
print('plane %d outlines processed'%z)
else:
Expand All @@ -657,7 +662,7 @@ def _masks_to_gui(parent, masks, outlines=None):
_,parent.outpix = np.unique(parent.outpix, return_inverse=True)
parent.outpix = np.reshape(parent.outpix, shape)

parent.ncells = np.uint16(parent.cellpix.max())
parent.ncells = parent.cellpix.max()
colors = parent.colormap[np.random.randint(0,1000,size=parent.ncells), :3]
parent.cellcolors = list(np.concatenate((np.array([[255,255,255]]), colors), axis=0).astype(np.uint8))
parent.draw_masks()
Expand Down
223 changes: 53 additions & 170 deletions notebooks/run_cellpose.ipynb

Large diffs are not rendered by default.

0 comments on commit a52a2ce

Please sign in to comment.