Repository: MouseLand/cellpose (language: python)

Issue:
Details on the application of this segmentation tool
Hi CellPose team,

Thank you for your amazing tool! I found it very promising. I have some questions about the application of this tool in practice.

1. What kind of images work best for the pre-trained model?
1.1 I found most of the images shown in the paper are either nuclei image or 1 cytoplasm and 1 nucleus RGB images.  Does this tool work on multiplexed images?
1.2 There is a parameter about 'diameter' on the website and I found all the images provided have similar cell types there. Will this tool work on images with very different cell types with different sizes?
1.3 Most of the images shown in the paper are in vitro. Have you tested on in vivo images?

2. If we train our own model with new data, how will the answers for the previous questions be different?

I am very excited to see promising tools for cell segmentation and curious about these questions for a better understanding of the tool. Thank you so much!


Discussion / hints:
1.1 There are two models you can switch between, nuclei and cells. 'Cells' always needs a cytoplasm channel, and it can have an optional nuclear channel. You would probably need to average or max-project your multiplexed images.

1.2 What cell types do you have in mind? Look at the figures in the paper for a representative set of images. It is important to set the **average** cell size approximately right, but then it will still find cells of different sizes around that average . 

1.3 We just took any images we could find, but you're welcome to contribute more images to the training dataset. The main in vivo images are neurons from calcium imaging experiments. 

2. You can in principle train with as many image input channels as you want, but then it will only work  for images with exactly those channels.  If all your images are from the same type of experiment, then the average cell size would be fixed and you don't need any resizing. We will release the notebooks for the full training pipeline, but you might have to wait a bit for that. Right now our priority is to develop the generalist model that can segment any type of image. 
Thank you for your detailed reply.

So for tumors, the average can be 30 pixels while immune can be 10 pixels. When you mention that it will still find cells of different sizes around that average, will it work in this case? 
I think so, but I can't really say without seeing an image. You'd have to try it, it's real easy if you just use the website (www.cellpose.org).   
I tried it and it misses small cells when it finds big cells. I was wondering if this can be fixed by new training samples or this is part of the fixed mechanism of the methods?
Can you show an example please? It's really hard to judge without seeing the results.
so for images with d=10, d=20, we can see every different result. It seems it is very parameters sensitive. It is less likely a problem for in vitro one cell type image. But for in vivo tissue, it can be a problem. But of course, the model has been amazing already. It is about the details.  

![d10](https://user-images.githubusercontent.com/16257776/73992857-6aed3b00-491e-11ea-9aa6-306c9ca527b0.png)
![d20](https://user-images.githubusercontent.com/16257776/73992861-6d4f9500-491e-11ea-845c-7a84f2277e1e.png)

Thanks for posting these results. By eye to me this image looks relatively ambiguous. Do you think you can confidently tell what the correct segmentation should have been? If so, it would be a good idea to contribute a manual segmentation of this to our training dataset via the GUI upload (see instructions in the readme).  

The main difference I see between the segmentations is that some ROIs get split or shrink a little with the smaller diameter, so if you prefer one segmentation over the other you can just choose the best d for you. 
The big d finds all the big cells while grouping two small cells into one. The small d misses big cells. 

My main concern is that the parameter here seems to have a very strong influence and I am not sure if this can be improved by more training data.
d is not a hyperparameter. It is meant to be set as the average cell diameter, whatever that might be. You can either use the automatic calibration, or input it yourself. 

It looks to me from your image that mostly the same cells are missed in both cases. This is simply because some cells are very out of focus which makes it impossible to segment them. The algorithm is automatically excluding them for you. In fact, I cannot tell in most cases where the cell boundaries are, can you? Have you tried d=15? 
All diameters have their own advantage and disadvantage but I think it is true that the data are not perfect. I think the model is good enough. Thanks!

Fix patch:
diff --git a/README.md b/README.md
index a589fa43..81c3088c 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,5 @@
-# Cellpose <img src="cellpose/logo/logo.png" width="250" title="cellpose" alt="cellpose" align="right" vspace = "50">
+# <p>  <b>Cellpose | </b> <img src="https://raw.githubusercontent.com/kevinjohncutler/cellpose/master/omnipose/logo.png?raw=True" height="33" title="omnipose" alt="omnipose" align="absmiddle" /> </p>
+<img src="https://raw.githubusercontent.com/kevinjohncutler/cellpose/master/cellpose/logo/logo.png?raw=True" width="250" title="cellpose" alt="cellpose" align="right" vspace = "50">
 
 [![Documentation Status](https://readthedocs.org/projects/cellpose/badge/?version=latest)](https://cellpose.readthedocs.io/en/latest/?badge=latest)
 [![Build Status](https://travis-ci.org/MouseLand/cellpose.svg?branch=master)](https://travis-ci.org/MouseLand/cellpose)
@@ -16,9 +17,15 @@
 
 A generalist algorithm for cell and nucleus segmentation. 
 
-This code was written by Carsen Stringer and Marius Pachitariu. To learn about Cellpose, read the [paper](https://t.co/kBMXmPp3Yn?amp=1) or watch the [talk](https://t.co/JChCsTD0SK?amp=1). For support, please open an [issue](https://github.com/MouseLand/cellpose/issues). 
+Cellpose was written by Carsen Stringer and Marius Pachitariu. To learn about Cellpose, read the [paper](https://t.co/kBMXmPp3Yn?amp=1) or watch the [talk](https://t.co/JChCsTD0SK?amp=1). For support, please open an [issue](https://github.com/MouseLand/cellpose/issues). 
 
-If you want to improve Cellpose for yourself and for everyone else, please consider contributing manual segmentations for a few of your images via the built-in GUI interface (see instructions below). 
+Omnipose was written by Kevin Cutler ([@kevinjohncutler](https://github.com/kevinjohncutler)). To learn about Omnipose, read the [paper](http://biorxiv.org/content/early/2021/11/04/2021.11.03.467199). 
+
+If you want to improve Cellpose/Omnipose for yourself and for everyone else, please consider contributing manual segmentations for a few of your images via the built-in GUI interface (see instructions below). 
+
+### UPDATE v0.7 (Nov 2021)
+
+Omnipose is now officially available and supported as part of Cellpose. Use the 'omni' flag and models to take advantage of it for long cells! (<i>E.g.</i>, filamentous bacteria.) Many additonal options are available and we will be updating the documentation shortly. 
 
 ### UPDATE v0.6 (Dec 2020)
 
diff --git a/cellpose/__main__.py b/cellpose/__main__.py
index 97414fff..c19ab59d 100644
--- a/cellpose/__main__.py
+++ b/cellpose/__main__.py
@@ -127,36 +127,7 @@ def main():
 
     args = parser.parse_args()
     
-    # omni changes not implemented for mxnet. Full parity for cpu/gpu in pytorch. 
-    if args.omni and args.mxnet:
-        logger.info('>>>> omni only implemented in pytorch.')
-        confirm = confirm_prompt('Continue with omni set to false?')
-        if not confirm:
-            exit()
-        else:
-            logger.info('>>>> omni set to false.')
-            args.omni = False
-
-    # For now, omni version is not compatible with 3D. WIP. 
-    if args.omni and args.do_3D:
-        logger.info('>>>> omni not yet compatible with 3D segmentation.')
-        confirm = confirm_prompt('Continue with omni set to false?')
-        if not confirm:
-            exit()
-        else:
-            logger.info('>>>> omni set to false.')
-            args.omni = False
-    
-    # omni model needs 4 classes. Would prefer a more elegant way to automaticaly update the flow fields
-    # instead of users deleting them manually - a check on the number of channels, maybe, or just use
-    # the yes/no prompt to ask the user if they want their flow fields in the given directory to be deleted. 
-    # would also need the look_one_level_down optionally toggled...
-    if args.omni and args.train:
-        logger.info('>>>> Training omni model. Setting nclasses to 4.')
-        logger.info('>>>> Make sure your flow fields are deleted and re-computed.')
-        args.nclasses = 4
-    
-                
+    # handle mxnet option 
     if args.check_mkl:
         mkl_enabled = models.check_mkl((not args.mxnet))
     else:
@@ -187,7 +158,7 @@ def main():
             imf = None
 
 
-        # Check with user
+        # Check with user if they REALLY mean to run without saving anything 
         if not (args.train or args.train_size):
             saving_something = args.save_png or args.save_tif or args.save_flows or args.save_ncolor or args.save_txt
             if not (saving_something or args.testing): 
@@ -199,10 +170,18 @@ def main():
                     
         device, gpu = models.assign_device((not args.mxnet), args.use_gpu)
 
+        #define available model names, right now we have three broad categories 
+        model_names = ['cyto','nuclei','bact','cyto2','bact_omni','cyto2_omni']
+        builtin_model = np.any([args.pretrained_model==s for s in model_names])
+        cytoplasmic = 'cyto' in args.pretrained_model
+        nuclear = 'nuclei' in args.pretrained_model
+        bacterial = 'bact' in args.pretrained_model
+        
         if not args.train and not args.train_size:
             tic = time.time()
-            if not (args.pretrained_model=='cyto' or args.pretrained_model=='nuclei' or args.pretrained_model=='cyto2'):
+            if not builtin_model:
                 cpmodel_path = args.pretrained_model
+                print('fghfghhfgh',cpmodel_path)
                 if not os.path.exists(cpmodel_path):
                     logger.warning('model path does not exist, using cyto model')
                     args.pretrained_model = 'cyto'
@@ -218,8 +197,10 @@ def main():
             logger.info('>>>> running cellpose on %d images using chan_to_seg %s and chan (opt) %s'%
                             (nimg, cstr0[channels[0]], cstr1[channels[1]]))
             logger.info('>>>> omni is %d, cluster is %d'%(args.omni,args.cluster))
-                    
-            if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei' or args.pretrained_model=='cyto2':
+            
+            
+            # handle built-in model exceptions; bacterial ones get no size model 
+            if builtin_model and not bacterial:
                 if args.mxnet and args.pretrained_model=='cyto2':
                     logger.warning('cyto2 model not available in mxnet, using cyto model')
                     args.pretrained_model = 'cyto'
@@ -232,9 +213,46 @@ def main():
                                              pretrained_model=cpmodel_path,
                                              torch=(not args.mxnet),
                                              nclasses=args.nclasses,omni=args.omni)
+            
+            # handle omnipose exceptions
+            if 'omni' in args.pretrained_model:
+                args.omni = True
+            
+            if args.omni:
+                logger.info('>>>> Omnipose is free for non-commercial use under the AGPL. For commercial licenses, contact uwcomotion@uw.edu.')
+    
+            # omni changes not implemented for mxnet. Full parity for cpu/gpu in pytorch. 
+            if args.omni and args.mxnet:
+                logger.info('>>>> omni only implemented in pytorch.')
+                confirm = confirm_prompt('Continue with omni set to false?')
+                if not confirm:
+                    exit()
+                else:
+                    logger.info('>>>> omni set to false.')
+                    args.omni = False
 
+            # For now, omni version is not compatible with 3D. WIP. 
+            if args.omni and args.do_3D:
+                logger.info('>>>> omni not yet compatible with 3D segmentation.')
+                confirm = confirm_prompt('Continue with omni set to false?')
+                if not confirm:
+                    exit()
+                else:
+                    logger.info('>>>> omni set to false.')
+                    args.omni = False
+
+            # omni model needs 4 classes. Would prefer a more elegant way to automaticaly update the flow fields
+            # instead of users deleting them manually - a check on the number of channels, maybe, or just use
+            # the yes/no prompt to ask the user if they want their flow fields in the given directory to be deleted. 
+            # would also need the look_one_level_down optionally toggled...
+            if args.omni and args.train:
+                logger.info('>>>> Training omni model. Setting nclasses to 4.')
+                logger.info('>>>> Make sure your flow fields are deleted and re-computed.')
+                args.nclasses = 4
+            
+            # handle diameters
             if args.diameter==0:
-                if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei' or args.pretrained_model=='cyto2':
+                if builtin_model:
                     diameter = None
                     logger.info('>>>> estimating diameter for each image')
                 else:
@@ -279,15 +297,17 @@ def main():
                                   save_txt=args.save_txt,in_folders=args.in_folders)
             logger.info('>>>> completed in %0.3f sec'%(time.time()-tic))
         else:
-            if args.pretrained_model=='cyto' or args.pretrained_model=='nuclei' or args.pretrained_model=='cyto2':
+            if builtin_model:
                 if args.mxnet and args.pretrained_model=='cyto2':
                     logger.warning('cyto2 model not available in mxnet, using cyto model')
                     args.pretrained_model = 'cyto'
                 cpmodel_path = models.model_path(args.pretrained_model, 0, not args.mxnet)
-                if args.pretrained_model=='cyto':
+                if cytoplasmic:
                     szmean = 30.
-                else:
+                elif nuclear:
                     szmean = 17.
+                elif bacterial:
+                    szmean = 0. #bacterial models are not rescaled 
             else:
                 cpmodel_path = os.fspath(args.pretrained_model)
                 szmean = 30.
diff --git a/cellpose/core.py b/cellpose/core.py
index e9acbc9a..863b940a 100644
--- a/cellpose/core.py
+++ b/cellpose/core.py
@@ -4,7 +4,6 @@
 from tqdm import trange, tqdm
 from urllib.parse import urlparse
 import tempfile
-from scipy.ndimage import median_filter
 import cv2
 from . import transforms, dynamics, utils, plot, metrics
 
@@ -35,8 +34,7 @@
 core_logger.setLevel(logging.DEBUG)
 tqdm_out = utils.TqdmToLogger(core_logger, level=logging.INFO)
 
-# no longer returns nclasses, as it was hard-coded; now it is specified by the user
-# (maybe it should be incorportated into the model name in a future version)
+# nclasses now specified by user or by model type in models.py
 def parse_model_string(pretrained_model):
     if isinstance(pretrained_model, list):
         model_str = os.path.split(pretrained_model[0])[-1]
diff --git a/cellpose/dynamics.py b/cellpose/dynamics.py
index f45d42dc..b1d847e6 100644
--- a/cellpose/dynamics.py
+++ b/cellpose/dynamics.py
@@ -1,8 +1,6 @@
 import time, os
 from scipy.ndimage.filters import maximum_filter1d
 from skimage import filters
-from scipy.ndimage.morphology import binary_dilation, binary_opening
-from skimage.measure import label, regionprops
 import torch
 import scipy.ndimage
 import numpy as np
@@ -10,7 +8,6 @@
 from tqdm import trange
 from numba import njit, float32, int32, vectorize
 import edt
-from skimage import measure
 import fastremap
 import cv2
 
@@ -19,6 +16,7 @@
 dynamics_logger.setLevel(logging.DEBUG)
 
 from . import utils, metrics, transforms
+from omnipose import omnipose
 
 try:
     import torch
@@ -30,12 +28,6 @@
 except:
     TORCH_ENABLED = False
 
-try:
-    from sklearn.cluster import DBSCAN
-    SKLEARN_ENABLED = True 
-except:
-    SKLEARN_ENABLED = False
-
 @njit('(float64[:], int32[:], int32[:], int32[:], int32[:], int32, int32, boolean)', nogil=True)
 def _extend_centers(T, y, x, ymed, xmed, Lx, niter, omni=False):
     """ run diffusion from center of mask (ymed, xmed) on mask pixels (y, x)
@@ -73,15 +65,8 @@ def _extend_centers(T, y, x, ymed, xmed, Lx, niter, omni=False):
     """
     for t in range(niter):
         if omni:
-            # solve Eikonal equation 
-            minx = np.minimum(T[y*Lx + x-1],T[y*Lx + x+1])
-            miny = np.minimum(T[(y-1)*Lx + x],T[(y+1)*Lx + x],)
-            mina = np.minimum(T[(y-1)*Lx + x-1],T[(y+1)*Lx + x+1])
-            minb = np.minimum(T[(y-1)*Lx + x+1],T[(y+1)*Lx + x-1])
-            A = np.where(np.abs(mina-minb) >= 2, np.minimum(mina,minb)+np.sqrt(2), (1./2)*(mina+minb+np.sqrt(4-(mina-minb)**2)))
-            B = np.where(np.abs(miny-minx) >= np.sqrt(2), np.minimum(miny,minx)+1, (1./2)*(miny+minx+np.sqrt(2-(miny-minx)**2)))
-            T[y*Lx + x] = np.sqrt(A*B)
-
+            # solve eikonal equation 
+            T[y*Lx + x] = omnipose.eikonal_update_cpu(T, y, x, Lx)
         else:
             # solve heat equation 
             T[ymed*Lx + xmed] += 1
@@ -114,20 +99,7 @@ def _extend_centers_gpu(neighbors, centers, isneighbor, Ly, Lx, n_iter=200, devi
 
     for t in range(n_iter):
         if omni:
-            # zero out the non-neighbor elements so that they do not participate in min
-            Tneigh = T[:, pt[:,:,0], pt[:,:,1]] 
-            Tneigh *= isneigh
-
-            # using flattened index for the lattice points, just like gradient below
-            minx = torch.minimum(Tneigh[:,3,:],Tneigh[:,5,:]) 
-            mina = torch.minimum(Tneigh[:,2,:],Tneigh[:,6,:])
-            miny = torch.minimum(Tneigh[:,1,:],Tneigh[:,7,:])
-            minb = torch.minimum(Tneigh[:,0,:],Tneigh[:,8,:])
-            
-            A = torch.where(torch.abs(mina-minb) >= 2, torch.minimum(mina,minb) + np.sqrt(2), (1./2)*(mina+minb+torch.sqrt(4-(mina-minb)**2)))
-            B = torch.where(torch.abs(miny-minx) >= np.sqrt(2), torch.minimum(miny,minx) + 1, (1./2)*(miny+minx+torch.sqrt(2-(miny-minx)**2)))
-            T[:, pt[4,:,0], pt[4,:,1]] = torch.sqrt(A*B)
-
+            T[:, pt[4,:,0], pt[4,:,1]] = omnipose.eikonal_update_gpu(T,pt,isneigh)
         else:
             T[:, meds[:,0], meds[:,1]] += 1
             Tneigh = T[:, pt[:,:,0], pt[:,:,1]] # T is square, but Tneigh is nimg x 9 x <number of points in mask>
@@ -196,7 +168,6 @@ def masks_to_flows_gpu(masks, dists, device=None, omni=False):
     neighbors = np.stack((neighborsY, neighborsX), axis=-1)
     
     if not omni: # do original centroid projection algrorithm
-        
         # get mask centers
         centers = np.array(scipy.ndimage.center_of_mass(masks_padded, labels=masks_padded, 
                                                         index=np.arange(1, masks_padded.max()+1))).astype(int)
@@ -210,7 +181,7 @@ def masks_to_flows_gpu(masks, dists, device=None, omni=False):
             centers[i,0] = yi[imin]
             centers[i,1] = xi[imin] 
             
-    else: # do omnipose lgorithm (see cpu flow code for more details)
+    else: # do omnipose algorithm (see cpu flow code for more details)
         centers = np.stack((y,x),axis=1)
     
     # get neighbor validator (not all neighbors are in same mask)
@@ -220,7 +191,7 @@ def masks_to_flows_gpu(masks, dists, device=None, omni=False):
     # set number of iterations
     if omni:
         # omniversion requires fewer
-        n_iter = utils.get_niter(dists)
+        n_iter = omnipose.get_niter(dists)
     else:
         slices = scipy.ndimage.find_objects(masks)
         ext = np.array([[sr.stop - sr.start + 1, sc.stop - sc.start + 1] for sr, sc in slices])
@@ -300,7 +271,7 @@ def masks_to_flows_cpu(masks, dists, device=None, omni=False):
                 # This is what I found to be the lowest possible number of iterations to guarantee convergence,
                 # but only for the omni model. Too small for center-pixel heat to diffuse to the ends. 
                 # I would like to explain why this works theoretically; it is emperically validated for now.
-                niter = utils.get_niter(dists)
+                niter = omnipose.get_niter(dists)
             else:
                 niter = 2*np.int32(np.ptp(x) + np.ptp(y))
             
@@ -511,7 +482,8 @@ def steps2D_interp(p, dP, niter, use_gpu=False, device=None, omni=False, calc_tr
             # align_corners default is False, just added to suppress warning
             dPt = torch.nn.functional.grid_sample(im, pt, align_corners=False)
             if omni:
-                dPt = dPt/(1+t) #this supression is key to the omnipose method
+                dPt /= omnipose.step_factor(t)
+            
             for k in range(2): #clamp the final pixel locations
                 pt[:,:,:,k] = torch.clamp(pt[:,:,:,k] + dPt[:,k,:,:], -1., 1.)
             
@@ -546,7 +518,7 @@ def steps2D_interp(p, dP, niter, use_gpu=False, device=None, omni=False, calc_tr
                 tr[:,:,t] = p.copy()
             map_coordinates(dP.astype(np.float32), p[0], p[1], dPt)
             if omni:
-                dPt = dPt/(1+t) #this supression is key to the omnipose method
+                dPt /= omnipose.step_factor(t)
             for k in range(len(p)):
                 p[k] = np.minimum(shape[k]-1, np.maximum(0, p[k] + dPt[k]))
         return p, tr
@@ -634,10 +606,9 @@ def steps2D(p, dP, inds, niter, omni=False, calc_trace=False):
             y = inds[j,0]
             x = inds[j,1]
             p0, p1 = int(p[0,y,x]), int(p[1,y,x])
-            if omni: # suppress each step 
-                step = dP[:,p0,p1]/(t+1)
-            else:
-                step = dP[:,p0,p1]
+            step = dP[:,p0,p1]
+            if omni:
+                step /= omnipose.step_factor(t)
             for k in range(p.shape[0]):
                 p[k,y,x] = min(shape[k]-1, max(0, p[k,y,x] + step[k]))
     return p, tr
@@ -711,8 +682,7 @@ def follow_flows(dP, mask=None, inds=None, niter=200, interp=True, use_gpu=True,
                                           device=device, omni=omni, calc_trace=calc_trace)
             
             p[:,inds[:,0],inds[:,1]] = p_interp
-    #print(p.shape)     
-    return p, inds, tr #, p_interp
+    return p, inds, tr
 
 def remove_bad_flow_masks(masks, flows, threshold=0.4, use_gpu=False, device=None, omni=False):
     """ remove masks which have inconsistent flows 
@@ -870,173 +840,45 @@ def get_masks(p, iscell=None, rpad=20, flows=None, threshold=0.4, use_gpu=False,
 
     return M0
 
-
-def smooth_distance(masks, dists=None, device=None, omni=False):
-    if device is None:
-        device = torch.device('cuda')
-    if dists is None:
-        dists = edt.edt(masks)
-        
-    pad = 1
-    
-    Ly0,Lx0 = masks.shape
-    Ly, Lx = Ly0+2*pad, Lx0+2*pad
-
-    masks_padded = np.pad(masks,pad)
-    
-    # get mask pixel neighbors
-    y, x = np.nonzero(masks_padded)
-
-    neighborsY = np.stack((y-1, y-1, y-1, 
-                           y  , y  , y  ,
-                           y+1, y+1, y+1), axis=0)
-    neighborsX = np.stack((x-1, x  , x+1, 
-                           x-1, x  , x+1, 
-                           x-1, x  , x+1), axis=0)
-    
-    neighbors = np.stack((neighborsY, neighborsX), axis=-1)
-    
-    centers = np.stack((y,x),axis=1)
-    
-    # get neighbor validator (not all neighbors are in same mask)
-    neighbor_masks = masks_padded[neighbors[:,:,0], neighbors[:,:,1]] #extract list of label values, 
-    isneighbor = neighbor_masks == neighbor_masks[4] # 4 corresponds to x,y now
-        
-    # set number of iterations
-    n_iter = utils.get_niter(dists)
-        
-    nimg = neighbors.shape[0] // 9
-    pt = torch.from_numpy(neighbors).to(device)
-    T = torch.zeros((nimg,Ly,Lx), dtype=torch.double, device=device)
-    meds = torch.from_numpy(centers.astype(int)).to(device)
-    isneigh = torch.from_numpy(isneighbor).to(device)
-
-    for t in range(n_iter):
-        # zero out the non-neighbor elements so that they do not participate in min
-        Tneigh = T[:, pt[:,:,0], pt[:,:,1]] 
-        Tneigh *= isneigh
-
-        # using flattened index for the lattice points, just like gradient below
-        minx = torch.minimum(Tneigh[:,3,:],Tneigh[:,5,:]) 
-        mina = torch.minimum(Tneigh[:,2,:],Tneigh[:,6,:])
-        miny = torch.minimum(Tneigh[:,1,:],Tneigh[:,7,:])
-        minb = torch.minimum(Tneigh[:,0,:],Tneigh[:,8,:])
-
-        A = torch.where(torch.abs(mina-minb) >= 2, torch.minimum(mina,minb) + np.sqrt(2), (1./2)*(mina+minb+torch.sqrt(4-(mina-minb)**2)))
-        B = torch.where(torch.abs(miny-minx) >= np.sqrt(2), torch.minimum(miny,minx) + 1, (1./2)*(miny+minx+torch.sqrt(2-(miny-minx)**2)))
-        T[:, pt[4,:,0], pt[4,:,1]] = torch.sqrt(A*B)
-
-    return T.cpu().squeeze().numpy()[pad:-pad,pad:-pad]
-
-
 def compute_masks(dP, dist, bd=None, p=None, inds=None, niter=200, dist_threshold=0.0, diam_threshold=12.,
                    flow_threshold=0.4, interp=True, cluster=False, do_3D=False, 
                    min_size=15, resize=None, omni=False, calc_trace=False, verbose=False,
                    use_gpu=False,device=None,nclasses=3):
     """ compute masks using dynamics from dP, dist, and boundary """
+    if verbose:
+         dynamics_logger.info('dist_threshold is %f',dist_threshold)
+    
     if omni or (inds is not None):
+        if verbose:
+            dynamics_logger.info('Using hysteresis threshold.')
         mask = filters.apply_hysteresis_threshold(dist, dist_threshold-1, dist_threshold) # good for thin features
     else:
         mask = dist > dist_threshold # analog to original iscell=(cellprob>cellprob_threshold)
 
     if np.any(mask): #mask at this point is a cell cluster binary map, not labels 
-        if not omni: # use original algorthm 
-            if verbose:
-                dynamics_logger.info('using original mask reconstruction algorithm')
-            if p is None:
-                p , inds, tr = follow_flows(dP * mask / 5., mask=mask, inds=inds, niter=niter, interp=interp, 
+        
+        #preprocess flows
+        if omni:
+            dP_ = omnipose.div_rescale(dP,mask)
+        else:
+            dP_ = dP * mask / 5.
+        
+        # follow flows
+        if p is None:
+                p , inds, tr = follow_flows(dP_, mask=mask, inds=inds, niter=niter, interp=interp, 
                                             use_gpu=use_gpu, device=device, omni=omni, calc_trace=calc_trace)
-            else: 
-                inds,tr = [],[]
-                if verbose:
-                    dynamics_logger.info('p given')
-            mask = get_masks(p, iscell=mask,flows=dP, threshold=flow_threshold if not do_3D else None, use_gpu=use_gpu)
-
-        else: # use new algorithm
-            Ly,Lx = mask.shape
-            if nclasses == 4:
-                dt = np.abs(dist[mask]) #abs needed if the threshold is negative
-                d = utils.dist_to_diam(dt)
-                eps = 1+1/3
-
-            else: #backwards compatibility, doesn't help for *clusters* of thin/small cells
-                d,e = utils.diameters(mask,omni)
-                eps = np.sqrt(2)
-
-            # save unaltered versions for later 
-            dP = dP.copy()
-
-            # The mean diameter can inform whether or not the cells are too small to form contiguous blobs.
-            # My first solution was to upscale everything before Euler integration to give pixels 'room' to
-            # stay together. My new solution is much better: use a clustering algorithm on the sub-pixel coordinates
-            # to assign labels. It works just as well and is faster because it doesn't require increasing the 
-            # number of points or taking time to upscale/downscale the data. Users can toggle cluster on manually or
-            # by setting the diameter threshold higher than the average diameter of the cells. 
-            if d <= diam_threshold:
-                cluster = True
-                if verbose:
-                    dynamics_logger.info('Turning on subpixel clustering for label continuity.')
-
-            dP *= mask 
-            dP = transforms.normalize_field(dP,omni=True)
-
-            # compute the divergence
-            Y, X = np.nonzero(mask)
-            pad = 1
-            Tx = np.zeros((Ly+2*pad)*(Lx+2*pad), np.float64)
-            Tx[Y*Lx+X] = np.reshape(dP[1].copy(),Ly*Lx)[Y*Lx+X]
-            Ty = np.zeros((Ly+2*pad)*(Lx+2*pad), np.float64)
-            Ty[Y*Lx+X] = np.reshape(dP[0].copy(),Ly*Lx)[Y*Lx+X]
-
-            # Rescaling by the divergence
-            div = np.zeros(Ly*Lx, np.float64)
-            div[Y*Lx+X]=(Ty[(Y+2)*Lx+X]+8*Ty[(Y+1)*Lx+X]-8*Ty[(Y-1)*Lx+X]-Ty[(Y-2)*Lx+X]+
-                         Tx[Y*Lx+X+2]+8*Tx[Y*Lx+X+1]-8*Tx[Y*Lx+X-1]-Tx[Y*Lx+X-2])
-            div = transforms.normalize99(div,omni=True)
-            div.shape = (Ly,Lx)
-            #add sigmoid on boundary output to help push pixels away - the final bit needed in some cases!
-            # specifically, places where adjacent cell flows are too colinear and therefore had low divergence
-#                 mag = div+1/(1+np.exp(-bd))
-            dP *= div
-
-            p, inds, tr = follow_flows(dP, mask, inds, interp=interp, use_gpu=use_gpu, device=device, omni=omni, calc_trace=calc_trace)
-
-            newinds = p[:,inds[:,0],inds[:,1]].swapaxes(0,1)
-            mask = np.zeros((p.shape[1],p.shape[2]))
-
-            # the eps parameter needs to be adjustable... maybe a function of the distance
-            if cluster and SKLEARN_ENABLED:
-                if verbose:
-                    dynamics_logger.info('Doing DBSCAN clustering with eps=%f'%eps)
-                db = DBSCAN(eps=eps, min_samples=3,n_jobs=8).fit(newinds)
-                labels = db.labels_
-                mask[inds[:,0],inds[:,1]] = labels+1
-            else:
-                newinds = np.rint(newinds).astype(int)
-                skelmask = np.zeros_like(dist, dtype=bool)
-                skelmask[newinds[:,0],newinds[:,1]] = 1
-
-                #disconnect skeletons at the edge, 5 pixels in 
-                border_mask = np.zeros(skelmask.shape, dtype=bool)
-                border_px =  border_mask.copy()
-                border_mask = binary_dilation(border_mask, border_value=1, iterations=5)
-
-                border_px[border_mask] = skelmask[border_mask]
-                if nclasses == 4: #can use boundary to erase joined edge skelmasks 
-                    border_px[bd>-1] = 0
-                    if verbose:
-                        dynamics_logger.info('Using boundary output to split edge defects')
-                else: #otherwise do morphological opening to attempt splitting 
-                    border_px = binary_opening(border_px,border_value=0,iterations=3)
-
-                skelmask[border_mask] = border_px[border_mask]
-
-                LL = label(skelmask,connectivity=1) 
-                mask[inds[:,0],inds[:,1]] = LL[newinds[:,0],newinds[:,1]]
-
-        # quality control - this got removed in recent version of cellpose??? or did I add it? 
-#             if flow_threshold is not None and flow_threshold > 0 and dP is not None:
-#                 mask = dynamics.remove_bad_flow_masks(mask, dP, threshold=flow_threshold, omni=omni)
+        else: 
+            tr = []
+            inds = np.stack(np.nonzero(mask)).T
+            if verbose:
+                dynamics_logger.info('p given')
+        
+        #calculate masks
+        if omni:
+            mask = omnipose.get_masks(p,bd,dist,mask,inds,nclasses,cluster=cluster,
+                                      diam_threshold=diam_threshold,verbose=verbose) 
+        else:
+            mask = get_masks(p, iscell=mask, flows=dP, threshold=flow_threshold if not do_3D else None, use_gpu=use_gpu)
 
         if resize is not None:
             if verbose:
diff --git a/cellpose/gui/gui.py b/cellpose/gui/gui.py
index 2255cc91..54e0a00c 100644
--- a/cellpose/gui/gui.py
+++ b/cellpose/gui/gui.py
@@ -13,10 +13,10 @@
 from scipy.ndimage import gaussian_filter
 
 from . import guiparts, menus, io
-from .. import models
-from ..utils import download_url_to_file, masks_to_outlines, normalize99
+from .. import models, core, dynamics
+from ..utils import download_url_to_file, masks_to_outlines
 from ..io import save_server
-from ..transforms import resize_image
+from ..transforms import resize_image, normalize99 #fixed import
 from ..plot import disk
 
 try:
@@ -33,6 +33,9 @@
 except:
     SERVER_UPLOAD = False
 
+#Define possible models; can we make a master list in another file to use in models and main? 
+MODEL_NAMES = ['cyto', 'nuclei', 'cyto2', 'cyto2_omni', 'bact_omni']
+    
 class QHLine(QFrame):
     def __init__(self):
         super(QHLine, self).__init__()
@@ -137,7 +140,7 @@ def run(image=None):
     app.setWindowIcon(app_icon)
     os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'
 
-    models.download_model_weights()
+    # models.download_model_weights() # does not exist
     MainW(image=image)
     ret = app.exec_()
     sys.exit(ret)
@@ -426,7 +429,7 @@ def make_buttons(self):
         b+=1
         # choose models
         self.ModelChoose = QComboBox()
-        self.ModelChoose.addItems(['cyto', 'nuclei', 'cyto2'])
+        self.ModelChoose.addItems(MODEL_NAMES) #added omnipose model names
         self.ModelChoose.setFixedWidth(70)
         self.ModelChoose.setStyleSheet(self.dropdowns)
         self.ModelChoose.setFont(self.medfont)
@@ -434,8 +437,11 @@ def make_buttons(self):
         label = QLabel('model: ')
         label.setStyleSheet(label_style)
         label.setFont(self.medfont)
-        label.setToolTip('there is a <em>cyto</em> model, a new <em>cyto2</em> model from user submissions, and a <em>nuclei</em> model')
-        self.ModelChoose.setToolTip('there is a <em>cyto</em> model, a new <em>cyto2</em> model from user submissions, and a <em>nuclei</em> model')
+        #update tooltip string 
+        tipstr = 'there is a <em>cyto</em> model, a new <em>cyto2</em> model from user submissions, a <em>nuclei</em> model, \
+                  and two omnipose models: <em>bact_omni</em> and <em>cyto2_omni</em>'
+        label.setToolTip(tipstr)
+        self.ModelChoose.setToolTip(tipstr)
         self.l0.addWidget(label, b, 0,1,1)
 
         b+=1
@@ -485,7 +491,7 @@ def make_buttons(self):
 
         b+=1
         label = QLabel('model match threshold:')
-        label.setToolTip('threshold on gradient match to accept a mask (set lower to get more cells)')
+        label.setToolTip('threshold on flow match to accept a mask (set lower to get more cells)')
         label.setStyleSheet(label_style)
         label.setFont(self.medfont)
         self.l0.addWidget(label, b, 0,1,2)
@@ -503,11 +509,12 @@ def make_buttons(self):
         self.threshslider.setEnabled(False)
         
         b+=1
-        label = QLabel('cell prob threshold:')
+        label = QLabel('cell threshold:')
+        label.setToolTip('threshold on scalar output field to seed cell masks \
+                        (set lower to include more pixels)')
         label.setStyleSheet(label_style)
         label.setFont(self.medfont)
         self.l0.addWidget(label, b, 0,1,2)
-        label.setToolTip('cell probability threshold (set lower to get more cells)')
         
         b+=1
         self.probslider = QSlider()
@@ -659,11 +666,11 @@ def check_gpu(self, torch=True):
         self.torch = torch
         self.useGPU.setChecked(False)
         self.useGPU.setEnabled(False)    
-        if self.torch and models.use_gpu(istorch=True):
+        if self.torch and core.use_gpu(istorch=True):
             self.useGPU.setEnabled(True)
             self.useGPU.setChecked(True)
         elif models.MXNET_ENABLED:
-            if models.use_gpu(istorch=False):
+            if core.use_gpu(istorch=False):
                 print('>>> will run model on GPU in mxnet <<<')
                 self.torch = False
                 self.useGPU.setEnabled(True)
@@ -1246,8 +1253,9 @@ def compute_saturation(self):
         # compute percentiles from stack
         self.saturation = []
         for n in range(len(self.stack)):
-            self.saturation.append([np.percentile(self.stack[n].astype(np.float32),1),
-                                    np.percentile(self.stack[n].astype(np.float32),99)])
+            # changed to use omnipose convention 
+            self.saturation.append([np.percentile(self.stack[n].astype(np.float32),0.01),
+                                    np.percentile(self.stack[n].astype(np.float32),99.99)])
 
     def chanchoose(self, image):
         if image.ndim > 2:
@@ -1287,12 +1295,13 @@ def compute_cprob(self):
             print('computing masks with cell prob=%0.3f, flow error threshold=%0.3f'%
                     (self.cellprob, thresh))
 
-        maski = self.model.cp._compute_masks(self.flows[4][:-1],
-                                             self.flows[4][-1],
-                                             p=self.flows[3].copy(),
-                                             cellprob_threshold=self.cellprob,
-                                             flow_threshold=thresh,
-                                             resize=self.cellpix.shape[-2:])[0]
+        maski = dynamics.compute_masks(self.flows[4][:-1], 
+                                       self.flows[4][-1],
+                                       p=self.flows[3].copy(),
+                                       dist_threshold=self.cellprob,
+                                       flow_threshold=thresh,
+                                       resize=self.cellpix.shape[-2:],
+                                       omni=self.omni)[0]
         
         self.masksOn = True
         self.outlinesOn = True
@@ -1323,12 +1332,21 @@ def compute_model(self):
             channels = self.get_channels()
             self.diameter = float(self.Diameter.text())
             try:
+                self.omni = 'omni' in self.current_model
+                bacterial = 'bact' in self.current_model
+                if self.omni:
+                    self.NetAvg.setCurrentIndex(2) #one run net
+                if bacterial:
+                    self.diameter = 0.
+                    
                 net_avg = self.NetAvg.currentIndex()<2
                 resample = self.NetAvg.currentIndex()==1
+                # print(data.shape,channels,self.diameter,resample,do_3D,net_avg)
+                print('net_avg',net_avg)
                 masks, flows, _, _ = self.model.eval(data, channels=channels,
                                                     diameter=self.diameter, invert=self.invert.isChecked(),
                                                     net_avg=net_avg, augment=False, resample=resample,
-                                                    do_3D=do_3D, progress=self.progress)
+                                                    do_3D=do_3D, progress=self.progress, omni=self.omni)
             except Exception as e:
                 print('NET ERROR: %s'%e)
                 self.progress.setValue(0)
@@ -1340,7 +1358,7 @@ def compute_model(self):
             #    masks = masks[0][np.newaxis,:,:]
             #    flows = flows[0]
             self.flows[0] = flows[0]
-            self.flows[1] = (np.clip(normalize99(flows[2].copy()),0,1) * 255).astype(np.uint8)
+            self.flows[1] = (normalize99(flows[2].copy(),omni=True) * 255).astype(np.uint8)
             if not do_3D:
                 masks = masks[np.newaxis,...]
                 self.flows[0] = resize_image(self.flows[0], masks.shape[-2], masks.shape[-1],
diff --git a/cellpose/gui/io.py b/cellpose/gui/io.py
index 64b4b678..2929faa9 100644
--- a/cellpose/gui/io.py
+++ b/cellpose/gui/io.py
@@ -38,7 +38,6 @@ def _load_image(parent, filename=None):
         return
     try:
         image = imread(filename)
-        image.shape
         parent.loaded = True
     except:
         print('images not compatible')
@@ -81,9 +80,7 @@ def _initialize_images(parent, image, resize, X2):
 
         if image.shape[-1] < 3:
             shape = image.shape
-            image = np.concatenate((image,
-                                       np.zeros((shape[0], shape[1], 3-shape[2]),
-                                        dtype=type(image[0,0,0]))), axis=-1)
+            image = np.concatenate((image,np.zeros((shape[0], shape[1], 3-shape[2]),dtype=type(image[0,0,0]))), axis=-1)
             if 3-shape[2]>1:
                 parent.onechan=True
             image = image[np.newaxis,...]
@@ -92,7 +89,7 @@ def _initialize_images(parent, image, resize, X2):
             image = image[np.newaxis,...]
     else:
         image = image[np.newaxis,...]
-
+    
     parent.stack = image
     parent.NZ = len(parent.stack)
     parent.scroll.setMaximum(parent.NZ-1)
@@ -115,7 +112,7 @@ def _initialize_images(parent, image, resize, X2):
         if X2!=0:
             img = transforms._X2zoom(img, X2=X2)
         parent.stack[k] = img
-
+    
     parent.imask=0
     print(parent.NZ, parent.stack[0].shape)
     parent.Ly, parent.Lx = img.shape[0], img.shape[1]
diff --git a/cellpose/io.py b/cellpose/io.py
index e562852c..ac178eaa 100644
--- a/cellpose/io.py
+++ b/cellpose/io.py
@@ -8,6 +8,7 @@
 import skimage
 
 from . import utils, plot, transforms
+from omnipose import omnipose
 
 try:
     from PyQt5 import QtGui, QtCore, Qt, QtWidgets
@@ -422,7 +423,7 @@ def save_masks(images, masks, flows, file_names, png=True, tif=False, channels=[
         check_dir(ncolordir)
         #convert masks to minimal n-color reresentation 
         imsave(os.path.join(ncolordir, basename + '_cp_ncolor_masks' + suffix + '.png'),
-               utils.ncolorlabel(masks))
+               omnipose.utils.ncolorlabel(masks))
     
     # save RGB flow picture
     if masks.ndim < 3 and save_flows:
diff --git a/cellpose/models.py b/cellpose/models.py
index a996b8e4..942c3062 100644
--- a/cellpose/models.py
+++ b/cellpose/models.py
@@ -11,10 +11,13 @@
 from . import transforms, dynamics, utils, plot
 from .core import UnetModel, assign_device, MXNET_ENABLED, parse_model_string
 
+from omnipose import omnipose
+
 _MODEL_URL = 'https://www.cellpose.org/models'
 _MODEL_DIR_ENV = os.environ.get("CELLPOSE_LOCAL_MODELS_PATH")
 _MODEL_DIR_DEFAULT = pathlib.Path.home().joinpath('.cellpose', 'models')
 MODEL_DIR = pathlib.Path(_MODEL_DIR_ENV) if _MODEL_DIR_ENV else _MODEL_DIR_DEFAULT
+MODEL_NAMES = ['cyto','nuclei','bact','cyto2','bact_omni','cyto2_omni']
 
 def model_path(model_type, model_index, use_torch):
     torch_str = 'torch' if use_torch else ''
@@ -69,15 +72,27 @@ def __init__(self, gpu=False, model_type='cyto', net_avg=True, device=None, torc
         sdevice, gpu = assign_device(self.torch, gpu)
         self.device = device if device is not None else sdevice
         self.gpu = gpu
+        
+        # set defaults and catch if cyto2 is being used without torch 
         model_type = 'cyto' if model_type is None else model_type
         if model_type=='cyto2' and not self.torch:
             model_type='cyto'
+                
+        self.omni = omni or 'omni' in model_type       
         
-        self.omni = omni        
+        # for now, omni models cannot do net_avg 
+        if self.omni:
+            net_avg = False
+        model_range = range(4) if net_avg else range(1)
+        self.pretrained_model = [model_path(model_type, j, torch) for j in model_range]
         
-        self.pretrained_model = [model_path(model_type, j, torch) for j in range(4)]
-        self.pretrained_size = size_model_path(model_type, torch)
-        self.diam_mean = 30. if model_type!='nuclei' else 17.
+        self.diam_mean = 30. #default for any cyto model 
+        nuclear = 'nuclei' in model_type
+        bacterial = 'bact' in model_type
+        if nuclear:
+            self.diam_mean = 17. 
+        elif bacterial:
+            self.diam_mean = 0.
         
         if not net_avg:
             self.pretrained_model = self.pretrained_model[0]
@@ -86,10 +101,15 @@ def __init__(self, gpu=False, model_type='cyto', net_avg=True, device=None, torc
                                 pretrained_model=self.pretrained_model,
                                 diam_mean=self.diam_mean, torch=self.torch, omni=self.omni)
         self.cp.model_type = model_type
-
-        self.sz = SizeModel(device=self.device, pretrained_size=self.pretrained_size,
-                            cp_model=self.cp)
-        self.sz.model_type = model_type
+        
+        # size model not used for bacterial model
+        if not bacterial:
+            self.pretrained_size = size_model_path(model_type, torch)
+            self.sz = SizeModel(device=self.device, pretrained_size=self.pretrained_size,
+                                cp_model=self.cp)
+            self.sz.model_type = model_type
+        else:
+            self.pretrained_size = None
 
     def eval(self, x, batch_size=8, channels=None, channel_axis=None, z_axis=None,
              invert=False, normalize=True, diameter=30., do_3D=False, anisotropy=None,
@@ -281,7 +301,7 @@ class CellposeModel(UnetModel):
     model_dir: str (optional, default None)
         overwrite the built in model directory where cellpose looks for models
     
-    omni: use omnipose flow field model (optional, default False)
+    omni: use omnipose model (optional, default False)
 
     """
     
@@ -299,48 +319,65 @@ def __init__(self, gpu=False, pretrained_model=False,
             pretrained_model = list(pretrained_model)
         elif isinstance(pretrained_model, str):
             pretrained_model = [pretrained_model]
-            
-        self.omni = omni        
+    
+        # initialize according to arguments 
+        # these are overwritten if a model requires it (bact_omni the most rectrictive)
+        self.omni = omni
         self.nclasses = nclasses 
+        self.diam_mean = diam_mean
         
         if model_type is not None or (pretrained_model and not os.path.exists(pretrained_model[0])):
             pretrained_model_string = model_type 
-            if (pretrained_model_string !='cyto' 
-                and pretrained_model_string !='nuclei' 
-                and pretrained_model_string != 'cyto2'
-                and pretrained_model_string !='omni') or pretrained_model_string is None: # plan to have a built-in omni model
+            if ~np.any([pretrained_model_string == s for s in MODEL_NAMES]): #also covers None case
                 pretrained_model_string = 'cyto'
-            pretrained_model = None 
             if (pretrained_model and not os.path.exists(pretrained_model[0])):
                 models_logger.warning('pretrained model has incorrect path')
             models_logger.info(f'>>{pretrained_model_string}<< model set to be used')
             
-            diam_mean = 30. if pretrained_model_string!='nuclei' else 17. # cyto2 still uses 17, right? 
+            nuclear = 'nuclei' in pretrained_model_string
+            bacterial = 'bact' in pretrained_model_string
+            
+            if nuclear:
+                self.diam_mean = 17. 
+            elif bacterial:
+                self.diam_mean = 0.
+
+            # set omni flag to true if the name contains it
+            self.omni = 'omni' in pretrained_model_string
             
-            pretrained_model = [model_path(pretrained_model_string, j, torch) for j in range(4)]
-            pretrained_model = pretrained_model[0] if not net_avg else pretrained_model 
+            #changed to only look for multiple files if net_avg is selected
+            model_range = range(4) if net_avg else range(1)
+            pretrained_model = [model_path(pretrained_model_string, j, torch) for j in model_range]
             residual_on, style_on, concatenation = True, True, False
         else:
             if pretrained_model:
-                params = parse_model_string(pretrained_model[0])
+                pretrained_model_string = pretrained_model[0]
+                params = parse_model_string(pretrained_model_string)
                 if params is not None:
-                    residual_on, style_on, concatenation = params #no more nclasses here, as it was hard-coded at 3, now defaults to 3... 
-                    # need to include it it the model name or extract it from the model itseld
-                
+                    residual_on, style_on, concatenation = params 
+                self.omni = 'omni' in pretrained_model_string
+        # must have four classes for omnipose models
+        # Note that omni can still be used independently for evaluation to 'mix and match'
+        #would be better just to read from the model 
+        if self.omni:
+            self.nclasses = 4       
+
         # initialize network
         super().__init__(gpu=gpu, pretrained_model=False,
-                         diam_mean=diam_mean, net_avg=net_avg, device=device,
+                         diam_mean=self.diam_mean, net_avg=net_avg, device=device,
                          residual_on=residual_on, style_on=style_on, concatenation=concatenation,
-                         nclasses=nclasses, torch=torch, nchan=nchan)
+                         nclasses=self.nclasses, torch=self.torch, nchan=nchan)
 
         self.unet = False
         self.pretrained_model = pretrained_model
         if self.pretrained_model and len(self.pretrained_model)==1:
             self.net.load_model(self.pretrained_model[0], cpu=(not self.gpu))
         ostr = ['off', 'on']
-        self.net_type = 'cellpose_residual_{}_style_{}_concatenation_{}'.format(ostr[residual_on],
-                                                                                ostr[style_on],
-                                                                                ostr[concatenation])
+        omnistr = ['','_omni'] #toggle by containing omni phrase 
+        self.net_type = 'cellpose_residual_{}_style_{}_concatenation_{}{}'.format(ostr[residual_on],
+                                                                                   ostr[style_on],
+                                                                                   ostr[concatenation],
+                                                                                   omnistr[omni]) 
     
     def eval(self, x, batch_size=8, channels=None, channel_axis=None, 
              z_axis=None, normalize=True, invert=False, 
@@ -639,7 +676,10 @@ def _run_cp(self, x, compute_masks=True, normalize=True, invert=False,
         
     def loss_fn(self, lbl, y):
         """ loss function between true labels lbl and prediction y """
-        if not self.omni: # original loss function 
+        if self.omni:
+             #loss function for omnipose field 
+            loss = omnipose.loss(self, lbl, y)
+        else: # original loss function 
             veci = 5. * self._to_device(lbl[:,1:])
             lbl  = self._to_device(lbl[:,0]>.5)
             loss = self.criterion(y[:,:2] , veci) 
@@ -647,34 +687,6 @@ def loss_fn(self, lbl, y):
                 loss /= 2.
             loss2 = self.criterion2(y[:,2] , lbl)
             loss = loss + loss2
-        
-        else: #loss function for omnipose field 
-            veci = self._to_device(lbl[:,2:4]) #scaled to 5 in augmentation 
-            dist = lbl[:,1] # now distance transform replaces probability
-            boundary =  lbl[:,5]
-            cellmask = dist>0
-            w =  self._to_device(lbl[:,7])  # new smooth, boundary-emphasized weight calculated with augmentations  
-            dist = self._to_device(dist)
-            boundary = self._to_device(boundary)
-            cellmask = self._to_device(cellmask).bool()
-            flow = y[:,:2] # 0,1
-            dt = y[:,2]
-            bd = y[:,3]
-            a = 10.
-         
-
-            wt = torch.stack((w,w),dim=1)
-            ct = torch.stack((cellmask,cellmask),dim=1) 
-            
-            loss1 = 10.*self.criterion12(flow,veci,wt)  #weighted MSE 
-            loss2 = self.criterion14(flow,veci,w,cellmask) #ArcCosDotLoss
-            loss3 = self.criterion11(flow,veci,wt,ct)/a # DerivativeLoss
-            loss4 = 2.*self.criterion2(bd,boundary)
-            loss5 = 2.*self.criterion15(flow,veci,w,cellmask) # loss on norm 
-            loss6 = 2.*self.criterion12(dt,dist,w) #weighted MSE 
-            loss7 = self.criterion11(dt.unsqueeze(1),dist.unsqueeze(1),w.unsqueeze(1),cellmask.unsqueeze(1))/a  
-
-            loss = loss1 + loss2 + loss3 + loss4 + loss5 + loss6 + loss7
         return loss        
 
 
diff --git a/cellpose/plot.py b/cellpose/plot.py
index 2ce85360..806a1b9d 100644
--- a/cellpose/plot.py
+++ b/cellpose/plot.py
@@ -9,9 +9,10 @@
 
 
 from . import utils, io, transforms
+from omnipose.utils import ncolorlabel, sinebow
 
 # modified to use sinebow color
-def dx_to_circ(dP,transparency=False):
+def dx_to_circ(dP,transparency=True):
     """ dP is 2 x Y x X => 'optic' flow representation """
     dP = np.array(dP)
     mag = transforms.normalize99(np.sqrt(np.sum(dP**2,axis=0)),omni=1)
@@ -70,7 +71,7 @@ def show_segmentation(fig, img, maski, flowi, channels=[0,0], file_name=None, om
     ax.axis('off')
 
     outlines = utils.masks_to_outlines(maski)
-    c = utils.sinebow(5)
+    c = sinebow(5)
     colors = np.array(list(c.values()))[1:] 
     
     # Image normalization to improve cell visibility under labels
@@ -83,7 +84,7 @@ def show_segmentation(fig, img, maski, flowi, channels=[0,0], file_name=None, om
     
     # the mask_overlay function changes colors (preserves only hue I think). The label2rgb function from
     # skimage.color works really well. 
-    overlay = color.label2rgb(utils.ncolorlabel(maski),img1,colors,bg_label=0,alpha=1/3)
+    overlay = color.label2rgb(ncolorlabel(maski),img1,colors,bg_label=0,alpha=1/3)
     overlay = np.uint8(np.clip(overlay, 0, 1)*255)
     overlay[maski==0] = img1[maski==0] #restore original level to background regions
 
diff --git a/cellpose/transforms.py b/cellpose/transforms.py
index fd55435b..25bed9e4 100644
--- a/cellpose/transforms.py
+++ b/cellpose/transforms.py
@@ -2,9 +2,6 @@
 import warnings
 import cv2
 import edt
-from skimage.filters import gaussian
-from skimage.util import random_noise
-from scipy.ndimage import median_filter, binary_dilation
 import fastremap
 
 import logging
@@ -12,6 +9,7 @@
 transforms_logger.setLevel(logging.DEBUG)
 
 from . import dynamics, utils
+from omnipose import omnipose
 
 def _taper_mask(ly=224, lx=224, sig=7.5):
     bsize = max(224, max(ly, lx))
@@ -192,12 +190,12 @@ def make_tiles(imgi, bsize=224, augment=False, tile_overlap=0.1):
 
 # needs to have a wider range to avoid weird effects with few cells in frame
 # also turns out previous formulation can give negative numbers, messes up log operations etc. 
-def normalize99(img,lower=0.01,upper=99.99,omni=False):
+def normalize99(Y,lower=0.01,upper=99.99,omni=False):
     """ normalize image so 0.0 is 0.01st percentile and 1.0 is 99.99th percentile """
-    X = img.copy()
     if omni:
-        X = np.interp(X, (np.percentile(X, lower), np.percentile(X, upper)), (0, 1))
+        X = omnipose.normalize99(Y)
     else:
+        X = Y.copy()
         x01 = np.percentile(X, 1)
         x99 = np.percentile(X, 99)
         X = (X - x01) / (x99 - x01)
@@ -622,6 +620,9 @@ def random_rotate_and_resize(X, Y=None, scale_range=1., gamma_range=0.5, xy = (2
         scale_range: float (optional, default 1.0)
             Range of resizing of images for augmentation. Images are resized by
             (1-scale_range/2) + scale_range * np.random.rand()
+        
+        gamma_range: float (optional, default 0.5)
+           Images are gamma-adjusted im**gamma for gamma in (1-gamma_range,1+gamma_range) 
 
         xy: tuple, int (optional, default (224,224))
             size of transformed images to return
@@ -646,221 +647,29 @@ def random_rotate_and_resize(X, Y=None, scale_range=1., gamma_range=0.5, xy = (2
             amount each image was resized by
 
     """
-    nimg = len(X)
-    dist_bg = 5 # background distance field is set to -dist_bg 
     scale_range = max(0, min(2, float(scale_range))) # limit overall range to [0,2] i.e. 1+-1 
     
     if inds is None: # only relevant when debugging 
+        nimg = len(X)
         inds = np.arange(nimg)
     
-    # backwards compatibility; completely 'stock', no gamma augmentation or any other extra frills. 
-    # [Y[i][1:] for i in inds] is necessary because the original transform function does not use masks (entry 0). 
-    # This used to be done in the original function call. 
-    if not omni:
+    if omni:
+        return omnipose.random_rotate_and_resize(X, Y=Y, scale_range=scale_range, gamma_range=gamma_range, 
+                                                 xy=xy, do_flip=do_flip, rescale=rescale, inds=inds)
+    else:
+        # backwards compatibility; completely 'stock', no gamma augmentation or any other extra frills. 
+        # [Y[i][1:] for i in inds] is necessary because the original transform function does not use masks (entry 0). 
+        # This used to be done in the original function call. 
         return original_random_rotate_and_resize(X, Y=[Y[i][1:] for i in inds], scale_range=scale_range, xy=xy,
                                                  do_flip=do_flip, rescale=rescale, unet=unet)
 
-    # While in other parts of Cellpose channels are put last by default, here we have chan x Ly x Lx 
-    if X[0].ndim>2:
-        nchan = X[0].shape[0] 
-    else:
-        nchan = 1 
-    imgi  = np.zeros((nimg, nchan, xy[0], xy[1]), np.float32)
-        
-    lbl = []
-    if Y is not None:
-        for n in range(nimg):
-            labels = Y[n].copy()
-            if labels.ndim<3:
-                labels = labels[np.newaxis,:,:]
-            dist = labels[1]
-            dist[dist==0] = - dist_bg
-            if labels.shape[0]<6:
-                bd = 5.*(labels[1]==1)
-                bd[bd==0] = -5.
-                labels = np.concatenate((labels, bd[np.newaxis,:]))# add a boundary layer
-            if labels.shape[0]<7:
-                mask = labels[0]>0
-                labels = np.concatenate((labels, mask[np.newaxis,:])) # add a mask layer
-            Y[n] = labels
-
-        if Y[0].ndim>2:
-            nt = Y[0].shape[0] +1 #(added one for weight array)
-        else:
-            nt = 1
-        lbl = np.zeros((nimg, nt, xy[0], xy[1]), np.float32)
-
-    scale = np.zeros((nimg,2), np.float32)
-    for n in range(nimg):
-        img = X[n].copy()
-        # use recursive function here to pass back single image that was cropped appropriately 
-        imgi[n], lbl[n], scale[n] = random_crop_warp(img, Y[n], nt, xy, nchan, scale[n], 
-                                                     rescale[n] if rescale is not None else None, 
-                                                     scale_range, gamma_range, do_flip, inds[n], dist_bg)
-        
-    return imgi, lbl, np.mean(scale) #for size training, must output scalar size (need to check this again)
-
-# This function allows a more efficient implementation for recursively checking that the random crop includes cell pixels.
-# Now it is rerun on a per-image basis if a crop fails to capture .1 percent cell pixels (minimum). 
-def random_crop_warp(img, Y, nt, xy, nchan, scale, rescale, scale_range, gamma_range, do_flip, ind, dist_bg, depth=0):
-    
-    if depth>20:
-        error_message = 'Sparse or over-dense image detected. Problematic index is: '+str(ind)
-        transforms_logger.critical(error_message)
-        raise ValueError(error_message)
-    
-    if depth>100:
-        error_message = 'Recusion depth exceeded. Check that your images contain cells and background within a typical crop. Failed index is: '+str(ind)
-        transforms_logger.critical(error_message)
-        raise ValueError(error_message)
-        return
-    
-    do_old = True # Recomputing flow will never work because labels are jagged...
-    lbl = np.zeros((nt, xy[0], xy[1]), np.float32)
-    numpx = xy[0]*xy[1]
-    
-    if Y is not None:
-        labels = Y.copy()
-        # We want the scale distibution to have a mean of 1
-        # There may be a better way to skew the distribution to
-        # interpolate the parameter space without skewing the mean 
-        ds = scale_range/2
-        if do_old:
-            scale = np.random.uniform(low=1-ds,high=1+ds,size=2) #anisotropic
-        else:
-            scale = [np.random.uniform(low=1-ds,high=1+ds,size=1)]*2 # isotropic
-        if rescale is not None:
-            scale *= 1. / rescale
-
-    # image dimensions are always the last two in the stack (again, convention here is different)
-    Ly, Lx = img.shape[-2:]
-
-    # generate random augmentation parameters
-    dg = gamma_range/2 
-    flip = np.random.choice([0,1])
-
-    if do_old:
-        theta = np.random.rand() * np.pi * 2
-    else:
-        theta = np.random.choice([0, np.pi/4, np.pi/2, 3*np.pi/4]) 
-
-    # random translation, take the difference between the scaled dimensions and the crop dimensions
-    dxy = np.maximum(0, np.array([Lx*scale[1]-xy[1],Ly*scale[0]-xy[0]]))
-    # multiplies by a pair of random numbers from -.5 to .5 (different for each dimension) 
-    dxy = (np.random.rand(2,) - .5) * dxy 
-
-    # create affine transform
-    cc = np.array([Lx/2, Ly/2])
-    # xy are the sizes of the cropped image, so this is the center coordinates minus half the difference
-    cc1 = cc - np.array([Lx-xy[1], Ly-xy[0]])/2 + dxy
-    # unit vectors from the center
-    pts1 = np.float32([cc,cc + np.array([1,0]), cc + np.array([0,1])])
-    # transformed unit vectors
-    pts2 = np.float32([cc1,
-            cc1 + scale*np.array([np.cos(theta), np.sin(theta)]),
-            cc1 + scale*np.array([np.cos(np.pi/2+theta), np.sin(np.pi/2+theta)])])
-    M = cv2.getAffineTransform(pts1,pts2)
-
-
-    method = cv2.INTER_LINEAR
-    # the mode determines what happens with out of bounds regions. If we recompute the flow, we can
-    # reflect all the scalar quantities then take the derivative. If we just rotate the field, then
-    # the reflection messes up the directions. For now, we are returning to the default of padding
-    # with zeros. In the future, we may only predict a scalar field and can use reflection to fill
-    # the entire FoV with data - or we can work out how to properly extend the flow field. 
-    if do_old:
-        mode = 0
-    else:
-        mode = cv2.BORDER_DEFAULT # Does reflection 
-        
-    label_method = cv2.INTER_NEAREST
-    if Y is not None:
-        for k in [0,1,2,3,4,5,6]: # was skipping 2 and 3, now not 
-            
-            if k==0:
-                l = labels[k]
-                lbl[k] = cv2.warpAffine(l, M, (xy[1],xy[0]), borderMode=mode, flags=label_method)
-
-                # check to make sure the region contains at enough cell pixels; if not, retry
-                cellpx = np.sum(lbl[0]>0)
-                cutoff = (numpx/1000) # .1 percent of pixels must be cells
-                if cellpx<cutoff or cellpx==numpx:
-                    return random_crop_warp(img, Y, nt, xy, nchan, scale, rescale, scale_range, gamma_range, do_flip, ind, dist_bg, depth=depth+1)
-
-            else:
-                lbl[k] = cv2.warpAffine(labels[k], M, (xy[1],xy[0]), borderMode=mode, flags=method)
-        
-
-        imgi  = np.zeros((nchan, xy[0], xy[1]), np.float32)
-        for k in range(nchan):
-            I = cv2.warpAffine(img[k], M, (xy[1],xy[0]),borderMode=mode, flags=method)
-            
-            # gamma agumentation 
-            gamma = np.random.uniform(low=1-dg,high=1+dg) 
-            imgi[k] = I ** gamma
-            
-            # percentile clipping augmentation 
-            dp = 10
-            dpct = np.random.triangular(left=0, mode=0, right=dp, size=2) # weighted toward 0
-            imgi[k] = normalize99(imgi[k],upper=100-dpct[0],lower=dpct[1],omni=True)
-            
-            # noise augmentation 
-            imgi[k] = random_noise(imgi[k], mode="poisson")
-        
-        if nt > 1:
-            
-            mask = lbl[6]
-            l = lbl[0].astype(int)
-#                 smooth_dist = lbl[n,4].copy()
-            dist = edt.edt(l,parallel=8) # raplace with smooth dist function 
-            lbl[5] = dist==1 # boundary 
-
-            if do_old:
-                v1 = lbl[3].copy() # x component
-                v2 = lbl[2].copy() # y component 
-                dy = (-v1 * np.sin(-theta) + v2*np.cos(-theta))
-                dx = (v1 * np.cos(-theta) + v2*np.sin(-theta))
-
-                lbl[3] = 5.*dx*mask # factor of 5 is applied here to rescale flow components to [-5,5] range 
-                lbl[2] = 5.*dy*mask
-                
-                smooth_dist = dynamics.smooth_distance(l,dist)
-                smooth_dist[dist<=0] = -dist_bg
-                lbl[1] = smooth_dist
-#                 dist[dist<=0] = -dist_bg
-#                 lbl[1] = dist
-            else:
-#                 _, _, smooth_dist, mu = dynamics.masks_to_flows_gpu(l,dists=dist,omni=omni) #would want to replace this with a dedicated dist-only function
-                lbl[3] = 5.*mu[1]
-                lbl[2] = 5.*mu[0]
-
-                smooth_dist[smooth_dist<=0] = -dist_bg
-                lbl[1] = smooth_dist
-
-            bg_edt = edt.edt(mask<0.5,black_border=True) #last arg gives weight to the border, which seems to always lose
-            cutoff = 9
-            lbl[7] = (gaussian(1-np.clip(bg_edt,0,cutoff)/cutoff,sigma=1)+0.5)
-    
-    # Moved to the end because it conflicted with the recursion. Also, flipping the crop is ultimately equivalent and slightly faster. 
-    if flip and do_flip:
-        imgi = imgi[..., ::-1]
-        if Y is not None:
-            lbl = lbl[..., ::-1]
-            if nt > 1:
-                lbl[3] = -lbl[3]
-    return imgi, lbl, scale
 
 # I have the omni flag here just in case, but it actually does not affect the tests
 def normalize_field(mu,omni=False):
     if not omni:
         mu /= (1e-20 + (mu**2).sum(axis=0)**0.5)
     else:   
-        mag = np.sqrt(np.nansum(mu**2,axis=0))
-        m = mag>0
-#         print('Mag stats',np.min(mag[m]),np.max(mag[m]),np.median(mag[m]),np.mean(mag[m]))
-        mu = np.divide(mu, mag, out=np.zeros_like(mu), where=np.logical_and(mag!=0,~np.isnan(mag)))
-        # idea: percent-wise cutoff to only boost nonzero pixels 
-        
+        mu = omnipose.normalize_field(mu) 
     return mu
 
 
diff --git a/cellpose/utils.py b/cellpose/utils.py
index 2ae50d6f..04e110df 100644
--- a/cellpose/utils.py
+++ b/cellpose/utils.py
@@ -9,15 +9,12 @@
 import numpy as np
 import colorsys
 import io
-import random
-import fastremap
 
-from numba import njit
 from skimage.morphology import remove_small_holes
-from scipy.ndimage.morphology import binary_dilation
-import edt 
+
 
 from . import metrics
+from omnipose.utils import format_labels
 
 class TqdmToLogger(io.StringIO):
     """
@@ -376,14 +373,8 @@ def diameters(masks, omni=False, dist_threshold=1):
         md /= (np.pi**0.5)/2
         return md, counts**0.5
     else: #new distance-field-derived diameter (aggrees with cicle but more general)
-        dt = edt.edt(np.int32(masks))
-        dt_pos = np.abs(dt[dt>=dist_threshold])
-        return dist_to_diam(np.abs(dt_pos)), None
+        return omnipose.diameters(masks), None
 
-# also used in models.py
-def dist_to_diam(dt_pos):
-    return 6*np.mean(dt_pos)
-#     return np.exp(3/2)*gmean(dt_pos[dt_pos>=gmean(dt_pos)])
 
 def radius_distribution(masks, bins):
     unique, counts = np.unique(masks, return_counts=True)
@@ -487,193 +478,3 @@ def fill_holes_and_remove_small_masks(masks, min_size=15, hole_size=3, scale_fac
     return masks
 
 
-
-#4-color algorthm based on https://forum.image.sc/t/relabel-with-4-colors-like-map/33564 
-def ncolorlabel(lab,n=4,conn=2):
-    # needs to be in standard label form
-    # but also needs to be in int32 data type ot work properly; the formatting automatically
-    # puts it into the smallest datatype to save space 
-    lab = format_labels(lab).astype(np.int32) 
-    idx = connect(lab, conn)
-    idx = mapidx(idx)
-    colors = render_net(idx, n=n, rand=10)
-    lut = np.ones(lab.max()+1, dtype=np.uint8)
-    for i in colors: lut[i] = colors[i]
-    lut[0] = 0
-    return lut[lab]
-
-def neighbors(shape, conn=1):
-    dim = len(shape)
-    block = generate_binary_structure(dim, conn)
-    block[tuple([1]*dim)] = 0
-    idx = np.where(block>0)
-    idx = np.array(idx, dtype=np.uint8).T
-    idx = np.array(idx-[1]*dim)
-    acc = np.cumprod((1,)+shape[::-1][:-1])
-    return np.dot(idx, acc[::-1])
-
-@njit(fastmath=True)
-def search(img, nbs):
-    s, line = 0, img.ravel()
-    rst = np.zeros((len(line),2), img.dtype)
-    for i in range(len(line)):
-        if line[i]==0:continue
-        for d in nbs:
-            if line[i+d]==0: continue
-            if line[i]==line[i+d]: continue
-            rst[s,0] = line[i]
-            rst[s,1] = line[i+d]
-            s += 1
-    return rst[:s]
-                            
-def connect(img, conn=1):
-    buf = np.pad(img, 1, 'constant')
-    nbs = neighbors(buf.shape, conn)
-    rst = search(buf, nbs)
-    if len(rst)<2:
-        return rst
-    rst.sort(axis=1)
-    key = (rst[:,0]<<16)
-    key += rst[:,1]
-    order = np.argsort(key)
-    key[:] = key[order]
-    diff = key[:-1]!=key[1:]
-    idx = np.where(diff)[0]+1
-    idx = np.hstack(([0], idx))
-    return rst[order][idx]
-
-def mapidx(idx):
-    dic = {}
-    for i in np.unique(idx): dic[i] = []
-    for i,j in idx:
-        dic[i].append(j)
-        dic[j].append(i)
-    return dic
-
-# create a connection mapping 
-def render_net(conmap, n=4, rand=12, depth=0, max_depth=5):
-    thresh = 1e4
-    if depth<max_depth:
-        nodes = list(conmap.keys())
-        np.random.seed(depth+1)
-        np.random.shuffle(nodes)
-        colors = dict(zip(nodes, [0]*len(nodes)))
-        counter = dict(zip(nodes, [0]*len(nodes)))
-        count = 0
-        while len(nodes)>0 and count<thresh:
-            count+=1
-            k = nodes.pop(0)
-            counter[k] += 1
-            hist = [1e4] + [0] * n
-            for p in conmap[k]:
-                hist[colors[p]] += 1
-            if min(hist)==0:
-                colors[k] = hist.index(min(hist))
-                counter[k] = 0
-                continue
-            hist[colors[k]] = 1e4
-            minc = hist.index(min(hist))
-            if counter[k]==rand:
-                counter[k] = 0
-                np.random.seed(count)
-                minc = np.random.randint(1,4)
-            colors[k] = minc
-            for p in conmap[k]:
-                if colors[p] == minc:
-                    nodes.append(p)
-        if count==thresh:
-            print(n,'-color algorthm failed,trying again with',n+1,'colors. Depth',depth)
-            colors = render_net(conmap,n+1,rand,depth+1,max_depth)
-        return colors
-    else:
-        print('N-color algorthm exceeded max depth of',max_depth)
-        return None
-
-
-# Generate a color dictionary for use in visualizing N-colored labels.  
-def sinebow(N,bg_color=[0,0,0,0]):
-    colordict = {0:bg_color}
-    for j in range(N): 
-        angle = j*2*np.pi / (N)
-        r = ((np.cos(angle)+1)/2)
-        g = ((np.cos(angle+2*np.pi/3)+1)/2)
-        b = ((np.cos(angle+4*np.pi/3)+1)/2)
-        colordict.update({j+1:[r,g,b,1]})
-    return colordict
-
-def rescale(T):
-    """Rescale array between 0 and 1"""
-    T = np.interp(T, (T[:].min(), T[:].max()), (0, 1))
-    return T
-
-# Kevin's version of remove_edge_masks, need to merge (this one is more flexible)
-def clean_boundary(labels,boundary_thickness=3,area_thresh=30):
-    """Delete boundary masks below a given size threshold. Default boundary thickness is 3px,
-    meaning masks that are 3 or fewer pixels from the boudnary will be candidates for removal. 
-    """
-    border_mask = np.zeros(labels.shape, dtype=bool)
-    border_mask = binary_dilation(border_mask, border_value=1, iterations=boundary_thickness)
-    clean_labels = np.copy(labels)
-    for cell_ID in np.unique(labels):
-        mask = labels==cell_ID 
-        area = np.count_nonzero(mask)
-        overlap = np.count_nonzero(np.logical_and(mask, border_mask))
-        if overlap > 0 and area<area_thresh and overlap/area >= 0.5: #only premove cells that are 50% or more edge px
-            clean_labels[mask] = 0
-    return clean_labels
-
-
-# Should work for 3D too. Could put into usigned integer form at the end... 
-# Also could use some parallelization 
-from skimage import measure
-def format_labels(labels, clean=False, min_area=9):
-    """
-    Puts labels into 'standard form', i.e. background=0 and cells 1,2,3,...,N-1,N.
-    Optional clean flag: disconnect and disjoint masks and discard small masks beflow min_area. 
-    min_area default is 9px. 
-    """
-    
-    # Labels are stored as a part of a float array in Cellpose, so it must be cast back here.
-    # some people also use -1 as background, so we must cast to the signed integar class. We
-    # can safely assume no 2D or 3D image will have more than 2^31 cells. Finally, cv2 does not
-    # play well with unsigned integers (saves to default uint8), so we cast to uint32. 
-    labels = labels.astype('int32') 
-    labels -= np.min(labels) 
-    labels = labels.astype('uint32') 
-    
-    # optional cleanup 
-    if clean:
-        inds = np.unique(labels)
-        for j in inds[inds>0]:
-            mask = labels==j
-            lbl = measure.label(mask)                       
-            regions = measure.regionprops(lbl)
-            regions.sort(key=lambda x: x.area, reverse=True)
-            if len(regions) > 1:
-                print('Warning - found mask with disjoint label.')
-                for rg in regions[1:]:
-                    if rg.area <= min_area:
-                        labels[rg.coords[:,0], rg.coords[:,1]] = 0
-                        print('secondary disjoint part smaller than min_area. Removing it.')
-                    else:
-                        print('secondary disjoint part bigger than min_area, relabeling. Area:',rg.area, 
-                              'Label value:',np.unique(labels[rg.coords[:,0], rg.coords[:,1]]))
-                        labels[rg.coords[:,0], rg.coords[:,1]] = np.max(labels)+1
-                        
-            rg0 = regions[0]
-            if rg0.area <= min_area:
-                labels[rg0.coords[:,0], rg0.coords[:,1]] = 0
-                print('Warning - found mask area less than', min_area)
-                print('Removing it.')
-        
-    fastremap.renumber(labels,in_place=True) # convenient to have unit increments from 1 to N cells
-    labels = fastremap.refit(labels) # put into smaller data type if possible 
-    return labels
-
-# By testing for convergence across a range of superellipses, I found that the following
-# ratio guarantees convergence. The edt() package gives a quick (but rough) distance field,
-# and it allows us to find a least upper bound for the number of iterations needed for our
-# smooth distance field computation. 
-def get_niter(dists):
-    return np.ceil(np.max(dists)*1.16).astype(int)+1
-
diff --git a/omnipose/README.md b/omnipose/README.md
new file mode 100644
index 00000000..a55f7b66
--- /dev/null
+++ b/omnipose/README.md
@@ -0,0 +1,23 @@
+<img src="logo3.png" width="200" title="bacteria" alt="bacteria" align="right" vspace = "0">
+<img src="logo.png" width="200" title="omnipose" alt="omnipose" align="center" vspace = "0">
+
+### Why use Omnipose
+Omnipose solves the over-segmentation problems of Cellpose on long, ansiotropic cells. This is particularly relevant for bacterial cells, but Omnipose is suitable for aribtrary cell shapes. 
+
+### How to use Omnipose
+To use Omnipose on bacterial cells, use `model_type=bact_omni`. For other cell types, try `model_type=cyto2_omni`. You can also use your own Cellpose models with `omni=True` to help solve problems with over-segmentatuon. 
+
+### More about Omnipose
+Omnipose builds on Cellpose in a number of ways described in our [paper](http://biorxiv.org/content/early/2021/11/04/2021.11.03.467199). It turns out that cell 'centers' are not well-defined, and this is a huge problem for any cells that are long and curved - generally leading to over-segmentation.
+
+To fix this, we turned to the distance field (also known as the distance transform). This morphology-independent field replaces the uniform cell probability field of Cellpose, and its gradient replaces the heat-derived flow field of Cellpose. 
+
+The distance field works the same way as cell probability output, meaning it can be thresholded (with the same values!) to seed cell masks. However, it carries a lot more information and we use it to refine the mask recontruction parameters when cells get too thin.
+
+The flow field points towards the skeleton of the cell, and we built a new mask recontruction algorithm to leverage this fact. While cellpose tends to over-segement long cells, Omnipose can segment cells of any morphology whatsoever.
+
+Omnipose as a fourth ouput class (as opposed to three in Cellpose). This extra output is a boundary probability field, which we found helped the network to make better predictions at cell boundaries. It is also useful in mask recontruction. 
+
+### Licensing
+Omnipose is completely free for non-commercial use. The code associated with Omnipose is dual-licensed under the
+[GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.en.html). For commercial use, contact uwcomotion@uw.edu. 
diff --git a/omnipose/header.png b/omnipose/header.png
new file mode 100644
index 00000000..7dc553b8
Binary files /dev/null and b/omnipose/header.png differ
diff --git a/omnipose/header2.png b/omnipose/header2.png
new file mode 100644
index 00000000..181f1435
Binary files /dev/null and b/omnipose/header2.png differ
diff --git a/omnipose/license.txt b/omnipose/license.txt
new file mode 100644
index 00000000..dba13ed2
--- /dev/null
+++ b/omnipose/license.txt
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/omnipose/logo.png b/omnipose/logo.png
new file mode 100644
index 00000000..668e9af4
Binary files /dev/null and b/omnipose/logo.png differ
diff --git a/omnipose/logo2.png b/omnipose/logo2.png
new file mode 100644
index 00000000..8a93355e
Binary files /dev/null and b/omnipose/logo2.png differ
diff --git a/omnipose/logo3.png b/omnipose/logo3.png
new file mode 100644
index 00000000..ecac9482
Binary files /dev/null and b/omnipose/logo3.png differ
diff --git a/omnipose/logo_big.png b/omnipose/logo_big.png
new file mode 100644
index 00000000..999c1365
Binary files /dev/null and b/omnipose/logo_big.png differ
diff --git a/omnipose/omnipose.py b/omnipose/omnipose.py
new file mode 100644
index 00000000..8c054b13
--- /dev/null
+++ b/omnipose/omnipose.py
@@ -0,0 +1,524 @@
+import numpy as np
+from numba import njit
+import cv2
+import edt
+from skimage.util import random_noise
+from skimage.filters import gaussian
+from scipy.ndimage import binary_dilation, binary_opening
+from skimage import measure
+
+try:
+    import torch
+    from torch import optim, nn
+    from . import resnet_torch
+    TORCH_ENABLED = True 
+    torch_GPU = torch.device('cuda')
+    torch_CPU = torch.device('cpu')
+except:
+    TORCH_ENABLED = False
+
+try:
+    from sklearn.cluster import DBSCAN
+    SKLEARN_ENABLED = True 
+except:
+    SKLEARN_ENABLED = False
+    
+import logging
+omnipose_logger = logging.getLogger(__name__)
+omnipose_logger.setLevel(logging.DEBUG)
+
+#utilities
+
+# By testing for convergence across a range of superellipses, I found that the following
+# ratio guarantees convergence. The edt() package gives a quick (but rough) distance field,
+# and it allows us to find a least upper bound for the number of iterations needed for our
+# smooth distance field computation. 
+def get_niter(dists):
+    return np.ceil(np.max(dists)*1.16).astype(int)+1
+
+def dist_to_diam(dt_pos):
+    return 6*np.mean(dt_pos)
+#     return np.exp(3/2)*gmean(dt_pos[dt_pos>=gmean(dt_pos)])
+
+def diameters(masks,dist_threshold=0):
+    dt = edt.edt(np.int32(masks))
+    dt_pos = np.abs(dt[dt>dist_threshold])
+    return dist_to_diam(np.abs(dt_pos))
+
+def normalize_field(mu):
+    mag = np.sqrt(np.nansum(mu**2,axis=0))
+    m = mag>0
+    mu = np.divide(mu, mag, out=np.zeros_like(mu), where=np.logical_and(mag!=0,~np.isnan(mag)))        
+    return mu
+
+def normalize99(Y,lower=0.01,upper=99.99):
+    """ normalize image so 0.0 is 0.01st percentile and 1.0 is 99.99th percentile """
+    X = Y.copy()
+    return np.interp(X, (np.percentile(X, lower), np.percentile(X, upper)), (0, 1))
+
+    
+# Omnipose distance field is built on the following modified FIM update. 
+
+@njit('(float64[:], int32[:], int32[:], int32)', nogil=True)
+def eikonal_update_cpu(T, y, x, Lx):
+    """Update for iterative solution of the eikonal equation on CPU."""
+    minx = np.minimum(T[y*Lx + x-1],T[y*Lx + x+1])
+    miny = np.minimum(T[(y-1)*Lx + x],T[(y+1)*Lx + x],)
+    mina = np.minimum(T[(y-1)*Lx + x-1],T[(y+1)*Lx + x+1])
+    minb = np.minimum(T[(y-1)*Lx + x+1],T[(y+1)*Lx + x-1])
+    
+    A = np.where(np.abs(mina-minb) >= 2, np.minimum(mina,minb)+np.sqrt(2), (1./2)*(mina+minb+np.sqrt(4-(mina-minb)**2)))
+    B = np.where(np.abs(miny-minx) >= np.sqrt(2), np.minimum(miny,minx)+1, (1./2)*(miny+minx+np.sqrt(2-(miny-minx)**2)))
+    
+    return np.sqrt(A*B)
+
+def eikonal_update_gpu(T,pt,isneigh):
+    """Update for iterative solution of the eikonal equation on GPU."""
+    
+    # zero out the non-neighbor elements so that they do not participate in min
+    Tneigh = T[:, pt[:,:,0], pt[:,:,1]] 
+    Tneigh *= isneigh
+
+    # using flattened index for the lattice points, just like gradient below
+    minx = torch.minimum(Tneigh[:,3,:],Tneigh[:,5,:]) 
+    mina = torch.minimum(Tneigh[:,2,:],Tneigh[:,6,:])
+    miny = torch.minimum(Tneigh[:,1,:],Tneigh[:,7,:])
+    minb = torch.minimum(Tneigh[:,0,:],Tneigh[:,8,:])
+
+    A = torch.where(torch.abs(mina-minb) >= 2, torch.minimum(mina,minb) + np.sqrt(2), (1./2)*(mina+minb+torch.sqrt(4-(mina-minb)**2)))
+    B = torch.where(torch.abs(miny-minx) >= np.sqrt(2), torch.minimum(miny,minx) + 1, (1./2)*(miny+minx+torch.sqrt(2-(miny-minx)**2)))
+
+    return torch.sqrt(A*B)
+
+def smooth_distance(masks, dists=None, device=None):
+    if device is None:
+        device = torch.device('cuda')
+    if dists is None:
+        dists = edt.edt(masks)
+        
+    pad = 1
+    
+    Ly0,Lx0 = masks.shape
+    Ly, Lx = Ly0+2*pad, Lx0+2*pad
+
+    masks_padded = np.pad(masks,pad)
+    
+    # get mask pixel neighbors
+    y, x = np.nonzero(masks_padded)
+
+    neighborsY = np.stack((y-1, y-1, y-1, 
+                           y  , y  , y  ,
+                           y+1, y+1, y+1), axis=0)
+    neighborsX = np.stack((x-1, x  , x+1, 
+                           x-1, x  , x+1, 
+                           x-1, x  , x+1), axis=0)
+    
+    neighbors = np.stack((neighborsY, neighborsX), axis=-1)
+    
+    centers = np.stack((y,x),axis=1)
+    
+    # get neighbor validator (not all neighbors are in same mask)
+    neighbor_masks = masks_padded[neighbors[:,:,0], neighbors[:,:,1]] #extract list of label values, 
+    isneighbor = neighbor_masks == neighbor_masks[4] # 4 corresponds to x,y now
+        
+    # set number of iterations
+    n_iter = get_niter(dists)
+        
+    nimg = neighbors.shape[0] // 9
+    pt = torch.from_numpy(neighbors).to(device)
+    T = torch.zeros((nimg,Ly,Lx), dtype=torch.double, device=device)
+    meds = torch.from_numpy(centers.astype(int)).to(device)
+    isneigh = torch.from_numpy(isneighbor).to(device)
+
+    for t in range(n_iter):
+        T[:, pt[4,:,0], pt[4,:,1]] = eikonal_update_gpu(T,pt,isneigh)
+
+    return T.cpu().squeeze().numpy()[pad:-pad,pad:-pad]
+
+# Omnipose requires (a) a special suppressed Euler step and (b) a special mask reconstruction algorithm. 
+
+# no reason to use njit here except for compatibility with jitted fuctions that call it 
+#this way, the same factor is used everywhere (CPU+-interp, GPU)
+@njit()
+def step_factor(t):
+    """ Euler integration suppression factor."""
+    return (1+t)
+
+def div_rescale(dP,mask):
+    dP = dP.copy()
+    dP *= mask 
+    dP = normalize_field(dP)
+
+    # compute the divergence
+    Y, X = np.nonzero(mask)
+    Ly,Lx = mask.shape
+    pad = 1
+    Tx = np.zeros((Ly+2*pad)*(Lx+2*pad), np.float64)
+    Tx[Y*Lx+X] = np.reshape(dP[1].copy(),Ly*Lx)[Y*Lx+X]
+    Ty = np.zeros((Ly+2*pad)*(Lx+2*pad), np.float64)
+    Ty[Y*Lx+X] = np.reshape(dP[0].copy(),Ly*Lx)[Y*Lx+X]
+
+    # Rescaling by the divergence
+    div = np.zeros(Ly*Lx, np.float64)
+    div[Y*Lx+X]=(Ty[(Y+2)*Lx+X]+8*Ty[(Y+1)*Lx+X]-8*Ty[(Y-1)*Lx+X]-Ty[(Y-2)*Lx+X]+
+                 Tx[Y*Lx+X+2]+8*Tx[Y*Lx+X+1]-8*Tx[Y*Lx+X-1]-Tx[Y*Lx+X-2])
+    div = normalize99(div)
+    div.shape = (Ly,Lx)
+    #add sigmoid on boundary output to help push pixels away - the final bit needed in some cases!
+    # specifically, places where adjacent cell flows are too colinear and therefore had low divergence
+#                 mag = div+1/(1+np.exp(-bd))
+    dP *= div
+    return dP
+
+def get_masks(p,bd,dist,mask,inds,nclasses=4,cluster=False,diam_threshold=12.,verbose=False):
+    """Omnipose mask recontruction algorithm."""
+    if nclasses == 4:
+        dt = np.abs(dist[mask]) #abs needed if the threshold is negative
+        d = dist_to_diam(dt)
+        eps = 1+1/3
+
+    else: #backwards compatibility, doesn't help for *clusters* of thin/small cells
+        d = diameters(mask)
+        eps = np.sqrt(2)
+
+    # The mean diameter can inform whether or not the cells are too small to form contiguous blobs.
+    # My first solution was to upscale everything before Euler integration to give pixels 'room' to
+    # stay together. My new solution is much better: use a clustering algorithm on the sub-pixel coordinates
+    # to assign labels. It works just as well and is faster because it doesn't require increasing the 
+    # number of points or taking time to upscale/downscale the data. Users can toggle cluster on manually or
+    # by setting the diameter threshold higher than the average diameter of the cells. 
+    if verbose:
+        omnipose_logger.info('Mean diameter is %f'%d)
+
+    if d <= diam_threshold:
+        cluster = True
+        if verbose:
+            omnipose_logger.info('Turning on subpixel clustering for label continuity.')
+    y,x = np.nonzero(mask)
+    newinds = p[:,inds[:,0],inds[:,1]].swapaxes(0,1)
+    mask = np.zeros((p.shape[1],p.shape[2]))
+    
+    # the eps parameter needs to be adjustable... maybe a function of the distance
+    if cluster and SKLEARN_ENABLED:
+        if verbose:
+            omnipose_logger.info('Doing DBSCAN clustering with eps=%f'%eps)
+        db = DBSCAN(eps=eps, min_samples=3,n_jobs=8).fit(newinds)
+        labels = db.labels_
+        mask[inds[:,0],inds[:,1]] = labels+1
+    else:
+        newinds = np.rint(newinds).astype(int)
+        skelmask = np.zeros_like(dist, dtype=bool)
+        skelmask[newinds[:,0],newinds[:,1]] = 1
+
+        #disconnect skeletons at the edge, 5 pixels in 
+        border_mask = np.zeros(skelmask.shape, dtype=bool)
+        border_px =  border_mask.copy()
+        border_mask = binary_dilation(border_mask, border_value=1, iterations=5)
+
+        border_px[border_mask] = skelmask[border_mask]
+        if nclasses == 4: #can use boundary to erase joined edge skelmasks 
+            border_px[bd>-1] = 0
+            if verbose:
+                omnipose_logger.info('Using boundary output to split edge defects')
+        else: #otherwise do morphological opening to attempt splitting 
+            border_px = binary_opening(border_px,border_value=0,iterations=3)
+
+        skelmask[border_mask] = border_px[border_mask]
+
+        LL = measure.label(skelmask,connectivity=1) 
+        mask[inds[:,0],inds[:,1]] = LL[newinds[:,0],newinds[:,1]]
+        
+    return mask
+
+
+
+# Omnipose has special training settings. Loss function and augmentation. 
+
+def random_rotate_and_resize(X, Y=None, scale_range=1., gamma_range=0.5, xy = (224,224), 
+                             do_flip=True, rescale=None, inds=None):
+    """ augmentation by random rotation and resizing
+
+        X and Y are lists or arrays of length nimg, with dims channels x Ly x Lx (channels optional)
+
+        Parameters
+        ----------
+        X: LIST of ND-arrays, float
+            list of image arrays of size [nchan x Ly x Lx] or [Ly x Lx]
+
+        Y: LIST of ND-arrays, float (optional, default None)
+            list of image labels of size [nlabels x Ly x Lx] or [Ly x Lx]. The 1st channel
+            of Y is always nearest-neighbor interpolated (assumed to be masks or 0-1 representation).
+            If Y.shape[0]==3, then the labels are assumed to be [cell probability, Y flow, X flow]. 
+
+        scale_range: float (optional, default 1.0)
+            Range of resizing of images for augmentation. Images are resized by
+            (1-scale_range/2) + scale_range * np.random.rand()
+            
+        gamma_range: float (optional, default 0.5)
+           Images are gamma-adjusted im**gamma for gamma in (1-gamma_range,1+gamma_range) 
+
+        xy: tuple, int (optional, default (224,224))
+            size of transformed images to return
+
+        do_flip: bool (optional, default True)
+            whether or not to flip images horizontally
+
+        rescale: array, float (optional, default None)
+            how much to resize images by before performing augmentations
+
+        Returns
+        -------
+        imgi: ND-array, float
+            transformed images in array [nimg x nchan x xy[0] x xy[1]]
+
+        lbl: ND-array, float
+            transformed labels in array [nimg x nchan x xy[0] x xy[1]]
+
+        scale: array, float
+            amount each image was resized by
+
+    """
+    dist_bg = 5 # background distance field is set to -dist_bg 
+
+    # While in other parts of Cellpose channels are put last by default, here we have chan x Ly x Lx 
+    if X[0].ndim>2:
+        nchan = X[0].shape[0] 
+    else:
+        nchan = 1 
+    
+    nimg = len(X)
+    imgi  = np.zeros((nimg, nchan, xy[0], xy[1]), np.float32)
+        
+    lbl = []
+    if Y is not None:
+        for n in range(nimg):
+            labels = Y[n].copy()
+            if labels.ndim<3:
+                labels = labels[np.newaxis,:,:]
+            dist = labels[1]
+            dist[dist==0] = - dist_bg
+            if labels.shape[0]<6:
+                bd = 5.*(labels[1]==1)
+                bd[bd==0] = -5.
+                labels = np.concatenate((labels, bd[np.newaxis,:]))# add a boundary layer
+            if labels.shape[0]<7:
+                mask = labels[0]>0
+                labels = np.concatenate((labels, mask[np.newaxis,:])) # add a mask layer
+            Y[n] = labels
+
+        if Y[0].ndim>2:
+            nt = Y[0].shape[0] +1 #(added one for weight array)
+        else:
+            nt = 1
+        lbl = np.zeros((nimg, nt, xy[0], xy[1]), np.float32)
+
+    scale = np.zeros((nimg,2), np.float32)
+    for n in range(nimg):
+        img = X[n].copy()
+        # use recursive function here to pass back single image that was cropped appropriately 
+        imgi[n], lbl[n], scale[n] = random_crop_warp(img, Y[n], nt, xy, nchan, scale[n], 
+                                                     rescale[n] if rescale is not None else None, 
+                                                     scale_range, gamma_range, do_flip, inds[n], dist_bg)
+        
+    return imgi, lbl, np.mean(scale) #for size training, must output scalar size (need to check this again)
+
+# This function allows a more efficient implementation for recursively checking that the random crop includes cell pixels.
+# Now it is rerun on a per-image basis if a crop fails to capture .1 percent cell pixels (minimum). 
+def random_crop_warp(img, Y, nt, xy, nchan, scale, rescale, scale_range, gamma_range, do_flip, ind, dist_bg, depth=0):
+    
+    if depth>20:
+        error_message = 'Sparse or over-dense image detected. Problematic index is: '+str(ind)
+        omnipose_logger.critical(error_message)
+        raise ValueError(error_message)
+    
+    if depth>100:
+        error_message = 'Recusion depth exceeded. Check that your images contain cells and background within a typical crop. Failed index is: '+str(ind)
+        omnipose_logger.critical(error_message)
+        raise ValueError(error_message)
+        return
+    
+    do_old = True # Recomputing flow will never work because labels are jagged...
+    lbl = np.zeros((nt, xy[0], xy[1]), np.float32)
+    numpx = xy[0]*xy[1]
+    
+    if Y is not None:
+        labels = Y.copy()
+        # We want the scale distibution to have a mean of 1
+        # There may be a better way to skew the distribution to
+        # interpolate the parameter space without skewing the mean 
+        ds = scale_range/2
+        if do_old:
+            scale = np.random.uniform(low=1-ds,high=1+ds,size=2) #anisotropic
+        else:
+            scale = [np.random.uniform(low=1-ds,high=1+ds,size=1)]*2 # isotropic
+        if rescale is not None:
+            scale *= 1. / rescale
+
+    # image dimensions are always the last two in the stack (again, convention here is different)
+    Ly, Lx = img.shape[-2:]
+
+    # generate random augmentation parameters
+    dg = gamma_range/2 
+    flip = np.random.choice([0,1])
+
+    if do_old:
+        theta = np.random.rand() * np.pi * 2
+    else:
+        theta = np.random.choice([0, np.pi/4, np.pi/2, 3*np.pi/4]) 
+
+    # random translation, take the difference between the scaled dimensions and the crop dimensions
+    dxy = np.maximum(0, np.array([Lx*scale[1]-xy[1],Ly*scale[0]-xy[0]]))
+    # multiplies by a pair of random numbers from -.5 to .5 (different for each dimension) 
+    dxy = (np.random.rand(2,) - .5) * dxy 
+
+    # create affine transform
+    cc = np.array([Lx/2, Ly/2])
+    # xy are the sizes of the cropped image, so this is the center coordinates minus half the difference
+    cc1 = cc - np.array([Lx-xy[1], Ly-xy[0]])/2 + dxy
+    # unit vectors from the center
+    pts1 = np.float32([cc,cc + np.array([1,0]), cc + np.array([0,1])])
+    # transformed unit vectors
+    pts2 = np.float32([cc1,
+            cc1 + scale*np.array([np.cos(theta), np.sin(theta)]),
+            cc1 + scale*np.array([np.cos(np.pi/2+theta), np.sin(np.pi/2+theta)])])
+    M = cv2.getAffineTransform(pts1,pts2)
+
+
+    method = cv2.INTER_LINEAR
+    # the mode determines what happens with out of bounds regions. If we recompute the flow, we can
+    # reflect all the scalar quantities then take the derivative. If we just rotate the field, then
+    # the reflection messes up the directions. For now, we are returning to the default of padding
+    # with zeros. In the future, we may only predict a scalar field and can use reflection to fill
+    # the entire FoV with data - or we can work out how to properly extend the flow field. 
+    if do_old:
+        mode = 0
+    else:
+        mode = cv2.BORDER_DEFAULT # Does reflection 
+        
+    label_method = cv2.INTER_NEAREST
+    if Y is not None:
+        for k in [0,1,2,3,4,5,6]: # was skipping 2 and 3, now not 
+            
+            if k==0:
+                l = labels[k]
+                lbl[k] = cv2.warpAffine(l, M, (xy[1],xy[0]), borderMode=mode, flags=label_method)
+
+                # check to make sure the region contains at enough cell pixels; if not, retry
+                cellpx = np.sum(lbl[0]>0)
+                cutoff = (numpx/1000) # .1 percent of pixels must be cells
+                if cellpx<cutoff or cellpx==numpx:
+                    return random_crop_warp(img, Y, nt, xy, nchan, scale, rescale, scale_range, gamma_range, do_flip, ind, dist_bg, depth=depth+1)
+
+            else:
+                lbl[k] = cv2.warpAffine(labels[k], M, (xy[1],xy[0]), borderMode=mode, flags=method)
+        
+
+        imgi  = np.zeros((nchan, xy[0], xy[1]), np.float32)
+        for k in range(nchan):
+            I = cv2.warpAffine(img[k], M, (xy[1],xy[0]),borderMode=mode, flags=method)
+            
+            # gamma agumentation 
+            gamma = np.random.uniform(low=1-dg,high=1+dg) 
+            imgi[k] = I ** gamma
+            
+            # percentile clipping augmentation 
+            dp = 10
+            dpct = np.random.triangular(left=0, mode=0, right=dp, size=2) # weighted toward 0
+            imgi[k] = normalize99(imgi[k],upper=100-dpct[0],lower=dpct[1])
+            
+            # noise augmentation 
+            imgi[k] = random_noise(imgi[k], mode="poisson")
+        
+        if nt > 1:
+            
+            mask = lbl[6]
+            l = lbl[0].astype(int)
+#                 smooth_dist = lbl[n,4].copy()
+            dist = edt.edt(l,parallel=8) # raplace with smooth dist function 
+            lbl[5] = dist==1 # boundary 
+
+            if do_old:
+                v1 = lbl[3].copy() # x component
+                v2 = lbl[2].copy() # y component 
+                dy = (-v1 * np.sin(-theta) + v2*np.cos(-theta))
+                dx = (v1 * np.cos(-theta) + v2*np.sin(-theta))
+
+                lbl[3] = 5.*dx*mask # factor of 5 is applied here to rescale flow components to [-5,5] range 
+                lbl[2] = 5.*dy*mask
+                
+                smooth_dist = smooth_distance(l,dist)
+                smooth_dist[dist<=0] = -dist_bg
+                lbl[1] = smooth_dist
+#                 dist[dist<=0] = -dist_bg
+#                 lbl[1] = dist
+            else:
+#                 _, _, smooth_dist, mu = dynamics.masks_to_flows_gpu(l,dists=dist,omni=omni) #would want to replace this with a dedicated dist-only function
+                lbl[3] = 5.*mu[1]
+                lbl[2] = 5.*mu[0]
+
+                smooth_dist[smooth_dist<=0] = -dist_bg
+                lbl[1] = smooth_dist
+
+            bg_edt = edt.edt(mask<0.5,black_border=True) #last arg gives weight to the border, which seems to always lose
+            cutoff = 9
+            lbl[7] = (gaussian(1-np.clip(bg_edt,0,cutoff)/cutoff,sigma=1)+0.5)
+    
+    # Moved to the end because it conflicted with the recursion. Also, flipping the crop is ultimately equivalent and slightly faster. 
+    if flip and do_flip:
+        imgi = imgi[..., ::-1]
+        if Y is not None:
+            lbl = lbl[..., ::-1]
+            if nt > 1:
+                lbl[3] = -lbl[3]
+    return imgi, lbl, scale
+
+def loss(self, lbl, y):
+    """ Loss function for Omnipose.
+    
+    Parameters
+    --------------
+    lbl: ND-array, float
+        transformed labels in array [nimg x nchan x xy[0] x xy[1]]
+        lbl[:,0] cell masks
+        lbl[:,1] distance fields
+        lbl[:,2:4] flow fields
+        lbl[:,4] distance fields
+        lbl[:,5] boundary fields    
+        lbl[:,6] thresholded mask layer 
+        lbl[:,7] boundary-emphasized weights        
+    
+    y:  ND-tensor, float
+        network predictions
+        y[:,:2] flow fields
+        y[:,2] distance fields
+        y[:,3] boundary fields
+    
+    """
+    
+    veci = self._to_device(lbl[:,2:4]) #scaled to 5 in augmentation 
+    dist = lbl[:,1] # now distance transform replaces probability
+    boundary =  lbl[:,5]
+    cellmask = dist>0
+    w =  self._to_device(lbl[:,7])  
+    dist = self._to_device(dist)
+    boundary = self._to_device(boundary)
+    cellmask = self._to_device(cellmask).bool()
+    flow = y[:,:2] # 0,1
+    dt = y[:,2]
+    bd = y[:,3]
+    a = 10.
+
+    wt = torch.stack((w,w),dim=1)
+    ct = torch.stack((cellmask,cellmask),dim=1) 
+
+    loss1 = 10.*self.criterion12(flow,veci,wt)  #weighted MSE 
+    loss2 = self.criterion14(flow,veci,w,cellmask) #ArcCosDotLoss
+    loss3 = self.criterion11(flow,veci,wt,ct)/a # DerivativeLoss
+    loss4 = 2.*self.criterion2(bd,boundary)
+    loss5 = 2.*self.criterion15(flow,veci,w,cellmask) # loss on norm 
+    loss6 = 2.*self.criterion12(dt,dist,w) #weighted MSE 
+    loss7 = self.criterion11(dt.unsqueeze(1),dist.unsqueeze(1),w.unsqueeze(1),cellmask.unsqueeze(1))/a  
+
+    return loss1 + loss2 + loss3 + loss4 + loss5 + loss6 + loss7
+
+
diff --git a/omnipose/utils.py b/omnipose/utils.py
new file mode 100644
index 00000000..3e459071
--- /dev/null
+++ b/omnipose/utils.py
@@ -0,0 +1,193 @@
+from skimage import measure
+import numpy as np
+
+from numba import njit
+from scipy.ndimage.morphology import binary_dilation
+from scipy.ndimage import generate_binary_structure
+import edt 
+import random
+import fastremap
+
+#4-color algorthm based on https://forum.image.sc/t/relabel-with-4-colors-like-map/33564 
+def ncolorlabel(lab,n=4,conn=2):
+    # needs to be in standard label form
+    # but also needs to be in int32 data type ot work properly; the formatting automatically
+    # puts it into the smallest datatype to save space 
+    lab = format_labels(lab).astype(np.int32) 
+    idx = connect(lab, conn)
+    idx = mapidx(idx)
+    colors = render_net(idx, n=n, rand=10)
+    lut = np.ones(lab.max()+1, dtype=np.uint8)
+    for i in colors: lut[i] = colors[i]
+    lut[0] = 0
+    return lut[lab]
+
+def neighbors(shape, conn=1):
+    dim = len(shape)
+    block = generate_binary_structure(dim, conn)
+    block[tuple([1]*dim)] = 0
+    idx = np.where(block>0)
+    idx = np.array(idx, dtype=np.uint8).T
+    idx = np.array(idx-[1]*dim)
+    acc = np.cumprod((1,)+shape[::-1][:-1])
+    return np.dot(idx, acc[::-1])
+
+@njit(fastmath=True)
+def search(img, nbs):
+    s, line = 0, img.ravel()
+    rst = np.zeros((len(line),2), img.dtype)
+    for i in range(len(line)):
+        if line[i]==0:continue
+        for d in nbs:
+            if line[i+d]==0: continue
+            if line[i]==line[i+d]: continue
+            rst[s,0] = line[i]
+            rst[s,1] = line[i+d]
+            s += 1
+    return rst[:s]
+                            
+def connect(img, conn=1):
+    buf = np.pad(img, 1, 'constant')
+    nbs = neighbors(buf.shape, conn)
+    rst = search(buf, nbs)
+    if len(rst)<2:
+        return rst
+    rst.sort(axis=1)
+    key = (rst[:,0]<<16)
+    key += rst[:,1]
+    order = np.argsort(key)
+    key[:] = key[order]
+    diff = key[:-1]!=key[1:]
+    idx = np.where(diff)[0]+1
+    idx = np.hstack(([0], idx))
+    return rst[order][idx]
+
+def mapidx(idx):
+    dic = {}
+    for i in np.unique(idx): dic[i] = []
+    for i,j in idx:
+        dic[i].append(j)
+        dic[j].append(i)
+    return dic
+
+# create a connection mapping 
+def render_net(conmap, n=4, rand=12, depth=0, max_depth=5):
+    thresh = 1e4
+    if depth<max_depth:
+        nodes = list(conmap.keys())
+        np.random.seed(depth+1)
+        np.random.shuffle(nodes)
+        colors = dict(zip(nodes, [0]*len(nodes)))
+        counter = dict(zip(nodes, [0]*len(nodes)))
+        count = 0
+        while len(nodes)>0 and count<thresh:
+            count+=1
+            k = nodes.pop(0)
+            counter[k] += 1
+            hist = [1e4] + [0] * n
+            for p in conmap[k]:
+                hist[colors[p]] += 1
+            if min(hist)==0:
+                colors[k] = hist.index(min(hist))
+                counter[k] = 0
+                continue
+            hist[colors[k]] = 1e4
+            minc = hist.index(min(hist))
+            if counter[k]==rand:
+                counter[k] = 0
+                np.random.seed(count)
+                minc = np.random.randint(1,4)
+            colors[k] = minc
+            for p in conmap[k]:
+                if colors[p] == minc:
+                    nodes.append(p)
+        if count==thresh:
+            print(n,'-color algorthm failed,trying again with',n+1,'colors. Depth',depth)
+            colors = render_net(conmap,n+1,rand,depth+1,max_depth)
+        return colors
+    else:
+        print('N-color algorthm exceeded max depth of',max_depth)
+        return None
+
+# Generate a color dictionary for use in visualizing N-colored labels.  
+def sinebow(N,bg_color=[0,0,0,0]):
+    colordict = {0:bg_color}
+    for j in range(N): 
+        angle = j*2*np.pi / (N)
+        r = ((np.cos(angle)+1)/2)
+        g = ((np.cos(angle+2*np.pi/3)+1)/2)
+        b = ((np.cos(angle+4*np.pi/3)+1)/2)
+        colordict.update({j+1:[r,g,b,1]})
+    return colordict
+
+def rescale(T):
+    """Rescale array between 0 and 1"""
+    T = np.interp(T, (T[:].min(), T[:].max()), (0, 1))
+    return T
+
+# Kevin's version of remove_edge_masks, need to merge (this one is more flexible)
+def clean_boundary(labels,boundary_thickness=3,area_thresh=30):
+    """Delete boundary masks below a given size threshold. Default boundary thickness is 3px,
+    meaning masks that are 3 or fewer pixels from the boudnary will be candidates for removal. 
+    """
+    border_mask = np.zeros(labels.shape, dtype=bool)
+    border_mask = binary_dilation(border_mask, border_value=1, iterations=boundary_thickness)
+    clean_labels = np.copy(labels)
+    for cell_ID in np.unique(labels):
+        mask = labels==cell_ID 
+        area = np.count_nonzero(mask)
+        overlap = np.count_nonzero(np.logical_and(mask, border_mask))
+        if overlap > 0 and area<area_thresh and overlap/area >= 0.5: #only premove cells that are 50% or more edge px
+            clean_labels[mask] = 0
+    return clean_labels
+
+
+# Should work for 3D too. Could put into usigned integer form at the end... 
+# Also could use some parallelization 
+
+def format_labels(labels, clean=False, min_area=9):
+    """
+    Puts labels into 'standard form', i.e. background=0 and cells 1,2,3,...,N-1,N.
+    Optional clean flag: disconnect and disjoint masks and discard small masks beflow min_area. 
+    min_area default is 9px. 
+    """
+    
+    # Labels are stored as a part of a float array in Cellpose, so it must be cast back here.
+    # some people also use -1 as background, so we must cast to the signed integar class. We
+    # can safely assume no 2D or 3D image will have more than 2^31 cells. Finally, cv2 does not
+    # play well with unsigned integers (saves to default uint8), so we cast to uint32. 
+    labels = labels.astype('int32') 
+    labels -= np.min(labels) 
+    labels = labels.astype('uint32') 
+    
+    # optional cleanup 
+    if clean:
+        inds = np.unique(labels)
+        for j in inds[inds>0]:
+            mask = labels==j
+            lbl = measure.label(mask)                       
+            regions = measure.regionprops(lbl)
+            regions.sort(key=lambda x: x.area, reverse=True)
+            if len(regions) > 1:
+                print('Warning - found mask with disjoint label.')
+                for rg in regions[1:]:
+                    if rg.area <= min_area:
+                        labels[rg.coords[:,0], rg.coords[:,1]] = 0
+                        print('secondary disjoint part smaller than min_area. Removing it.')
+                    else:
+                        print('secondary disjoint part bigger than min_area, relabeling. Area:',rg.area, 
+                              'Label value:',np.unique(labels[rg.coords[:,0], rg.coords[:,1]]))
+                        labels[rg.coords[:,0], rg.coords[:,1]] = np.max(labels)+1
+                        
+            rg0 = regions[0]
+            if rg0.area <= min_area:
+                labels[rg0.coords[:,0], rg0.coords[:,1]] = 0
+                print('Warning - found mask area less than', min_area)
+                print('Removing it.')
+        
+    fastremap.renumber(labels,in_place=True) # convenient to have unit increments from 1 to N cells
+    labels = fastremap.refit(labels) # put into smaller data type if possible 
+    return labels
+
+
+
diff --git a/setup.py b/setup.py
index 88ea2cc4..b79f1d69 100644
--- a/setup.py
+++ b/setup.py
@@ -32,7 +32,8 @@
 
 with open("README.md", "r") as fh:
     long_description = fh.read()
-
+    
+    
 setup(
     name="cellpose",
     license="BSD",


Test patch:
diff --git a/tests/test_output.py b/tests/test_output.py
index c093ca3e..c129f388 100644
--- a/tests/test_output.py
+++ b/tests/test_output.py
@@ -11,6 +11,7 @@
 
 r_tol, a_tol = 1e-2, 1e-2
 
+
 def clear_output(data_dir, image_names):
     data_dir_2D = data_dir.joinpath('2D')
     data_dir_3D = data_dir.joinpath('2D')
diff --git a/tests/test_train.py b/tests/test_train.py
index 93844804..8a88eb30 100644
--- a/tests/test_train.py
+++ b/tests/test_train.py
@@ -6,6 +6,8 @@
 
 os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
 
+
+
 def test_class_train(data_dir):
     train_dir = str(data_dir.joinpath('2D').joinpath('train'))
     model_dir = str(data_dir.joinpath('2D').joinpath('train').joinpath('models'))
@@ -19,6 +21,10 @@ def test_class_train(data_dir):
     print('>>>> model trained and saved to %s'%cpmodel_path)
         
 def test_cli_train(data_dir):
+    # import sys
+    # path_root = Path(__file__).parents[1]
+    # sys.path.append(str(path_root))
+    # print(Path(__file__).parents[0],Path(__file__).parents[1],Path(__file__).parents[2])
     train_dir = str(data_dir.joinpath('2D').joinpath('train'))
     model_dir = str(data_dir.joinpath('2D').joinpath('train').joinpath('models'))
     shutil.rmtree(model_dir, ignore_errors=True)