def test_class_2D(data_dir, image_names): clear_output(data_dir, image_names) img = io.imread(str(data_dir.joinpath('2D').joinpath('rgb_2D.png'))) model_types = ['nuclei'] chan = [1] chan2 = [0] for m,model_type in enumerate(model_types): model = models.Cellpose(model_type=model_type) masks, flows, _, _ = model.eval(img, diameter=0, channels=[chan[m],chan2[m]], net_avg=False) io.imsave(str(data_dir.joinpath('2D').joinpath('rgb_2D_cp_masks.png')), masks) compare_masks(data_dir, ['rgb_2D.png'], '2D', model_type) clear_output(data_dir, image_names) if MATPLOTLIB: fig = plt.figure(figsize=(8,3)) plot.show_segmentation(fig, img, masks, flows[0], channels=[chan[m],chan2[m]])
def disp_2d_slice(self): """Display 3D segmentation results squeezed along z-axis""" # squeeze 3D prediction along z-axis, # assign unique integers to individual predictions pred = self.masks # prediction of 3D segmentation pred_squeezed = (pred.sum(0) > 0).astype(np.uint8) pred_labels, n_cells = ndi.label(pred_squeezed) fig = plt.figure(figsize=(12, 5)) img_2d = self.frame[self.n_layers // 2].astype(np.float) if self.multi_channel: img_2d = self._rgb2gray(img_2d) cp_plot.show_segmentation(fig, img_2d, pred_labels, self.flows, channels=self.channels) plt.tight_layout() plt.show()
def save_to_png(images, masks, flows, file_names): """ save nicely plotted segmentation image to png """ nimg = len(images) for n in range(nimg): img = images[n].copy() if img.ndim < 3: img = img[:, :, np.newaxis] elif img.shape[0] < 8: np.transpose(img, (1, 2, 0)) base = os.path.splitext(file_names[n])[0] with warnings.catch_warnings(): warnings.simplefilter("ignore") skimage.io.imsave(base + '_cp_masks.png', masks[n].astype(np.uint16)) maski = masks[n] flowi = flows[n][0] fig = plt.figure(figsize=(12, 3)) # can save images (set save_dir=None if not) plot.show_segmentation(fig, img, maski, flowi) fig.savefig(base + '_cp.png', dpi=300) plt.close(fig)
def main(inputs, img_path, img_format, output_dir): """ Parameter --------- inputs : str File path to galaxy tool parameter img_path : str File path for the input image img_format : str One of the ['ome.tiff', 'tiff', 'png', 'jpg'] output_dir : str Folder to save the outputs. """ warnings.simplefilter('ignore') with open(inputs, 'r') as param_handler: params = json.load(param_handler) gpu = params['use_gpu'] omni = params['omni'] model_selector = params['model_selector'] model_type = model_selector['model_type'] chan = model_selector['chan'] chan2 = model_selector['chan2'] if chan is None: channels = None else: channels = [int(chan), int(chan2) if chan2 is not None else None] options = params['options'] img = skimage.io.imread(img_path) print(f"Image shape: {img.shape}") # transpose to Ly x Lx x nchann and reshape based on channels if img_format.endswith('tiff') and params['channel_first']: img = np.transpose(img, (1, 2, 0)) img = transforms.reshape(img, channels=channels) channels = [1, 2] print(f"Image shape: {img.shape}") model = models.Cellpose(gpu=gpu, model_type=model_type, net_avg=options['net_avg'], omni=omni) masks, flows, styles, diams = model.eval(img, channels=channels, omni=omni, **options) # save masks to tiff with warnings.catch_warnings(): warnings.simplefilter("ignore") skimage.io.imsave(os.path.join(output_dir, 'cp_masks.tif'), masks.astype(np.uint16)) # make segmentation show # if params['show_segmentation']: img = skimage.io.imread(img_path) # uniform image if img_format.endswith('tiff') and params['channel_first']: img = np.transpose(img, (1, 2, 0)) img = transforms.reshape(img, channels=channels) channels = [1, 2] maski = masks flowi = flows[0] fig = plt.figure(figsize=(12, 3)) # can save images (set save_dir=None if not) plot.show_segmentation(fig, img, maski, flowi, channels=channels) fig.savefig(os.path.join(output_dir, 'segm_show.png'), dpi=300) plt.close(fig)
def cellpose_predict(data, config, path_save, callback_log=None): """ Perform prediction with CellPose. Parameters ---------- data : dict Contains data on which prediction should be performed. config : dict Configuration of CellPose prediction. path_save : pathline Path object Path where results will be saved. """ # Get data imgs = data['imgs'] file_names = data['file_names'] sizes_orginal = data['sizes_orginal'] channels = data['channels'] new_size = data['new_size'] obj_name = data['obj_name'] # Get config model_type = config['model_type'] obj_size = config['obj_size'] device = config['device'] log_message(f'\nPerforming segmentation of {obj_name}\n', callback_fun=callback_log) start_time = time.time() if not path_save.is_dir(): path_save.mkdir() # Perform segmentation with CellPose model = models.Cellpose( device, model_type=model_type) # model_type can be 'cyto' or 'nuclei' masks, flows, styles, diams = model.eval(imgs, diameter=obj_size, channels=channels) # Display and save results log_message(f'\n Creating outputs ...\n', callback_fun=callback_log) n_img = len(imgs) for idx in tqdm(range(n_img)): file_name = file_names[idx] maski = masks[idx] flowi = flows[idx][0] imgi = imgs[idx] # Rescale each channel separately imgi_rescale = imgi.copy() for idim in range(3): imgdum = imgi[:, :, idim] pa, pb = np.percentile(imgdum, (0.1, 99.9)) imgi_rescale[:, :, idim] = rescale_intensity( imgdum, in_range=(pa, pb), out_range=np.uint8).astype('uint8') # Save overview image fig = plt.figure(figsize=(12, 3)) plot.show_segmentation(fig, imgi_rescale.astype('uint8'), maski, flowi, channels=channels) plt.tight_layout() plt.savefig(path_save / f'{file_name.stem}__segment__{obj_name}.png', dpi=600) plt.close() # Save mask and flow images imsave(path_save / f'{file_name.stem}__flow__{obj_name}.png', flowi, check_contrast=False) if new_size: mask_full = resize_mask(maski, sizes_orginal[idx]) imsave(path_save / f'{file_name.stem}__mask__{obj_name}.png', mask_full.astype('uint16'), check_contrast=False) imsave(path_save / f'{file_name.stem}__mask_resize__{obj_name}.png', maski.astype('uint16'), check_contrast=False) else: imsave(path_save / f'{file_name.stem}__mask__{obj_name}.png', maski.astype('uint16'), check_contrast=False) log_message( f"\nSegmentation of provided images finished ({(time.time() - start_time)}s)", callback_fun=callback_log)
# if diameter is set to None, the size of the cells is estimated on a per image basis # you can set the average cell `diameter` in pixels yourself (recommended) # diameter can be a list or a single number for all images masks, flows, styles, diams = model.eval(imgs, diameter=diameter, channels=channels,cellprob_threshold= cellprob_threshold,flow_threshold=flow_threshold) # DISPLAY RESULTS from cellpose import plot nimg = len(imgs) for idx in range(nimg): maski = masks[idx] flowi = flows[idx][0] fig = plt.figure(figsize = (25,15)) plot.show_segmentation(fig, imgs[idx], maski, flowi, channels=channels[idx]) plt.savefig(os.path.join(summary_path,img_list[idx].replace('.tif','') +'_summary.png'),format = 'png',dpi = 216,bbox_inches = 'tight') plt.close() ## EXTRACT COORDINATE FOR EACH ROI # reload imgs imgs = [skimage.io.imread(os.path.join(img_path,f)) for f in img_list] import pandas as pd # detecting center of mass for each mask and creating a 2d-array as a roi image centers = [[list(ndimage.center_of_mass((np.ones(mask.shape)*[mask == k])[0])) for k in np.unique(mask)[1:]] for idx,mask in enumerate(masks)] dfs = [] rois = [] for c,center in enumerate(centers):
def cellpose_predict(data, config, path_save, callback_log=None): """ Perform prediction with CellPose. Parameters ---------- data : dict Contains data on which prediction should be performed. config : dict Configuration of CellPose prediction. path_save : pathline Path object Path where results will be saved. """ # Get data imgs = data['imgs'] file_names = data['file_names'] channels = data['channels'] obj_name = data['obj_name'] sizes_orginal = data['sizes_orginal'] new_size = data['new_size'] # Get config model_type = config['model_type'] diameter = config['diameter'] net_avg = config['net_avg'] resample = config['resample'] log_message(f'\nPerforming segmentation of {obj_name}\n', callback_fun=callback_log) start_time = time.time() if not path_save.is_dir(): path_save.mkdir() # Perform segmentation with CellPose model = models.Cellpose( gpu=False, model_type=model_type) # model_type can be 'cyto' or 'nuclei' masks, flows, styles, diams = model.eval(imgs, diameter=diameter, channels=channels, net_avg=net_avg, resample=resample) # Display and save results log_message(f'\n Creating outputs ...\n', callback_fun=callback_log) n_img = len(imgs) for idx in tqdm(range(n_img)): # Get images and file-name file_name = file_names[idx] maski = masks[idx] flowi = flows[idx][0] imgi = imgs[idx] # Rescale each channel separately imgi_norm = imgi.copy() for idim in range(3): imgdum = imgi[:, :, idim] # Renormalize to 8bit between 1 and 99 percentile pa = np.percentile(imgdum, 0.5) pb = np.percentile(imgdum, 99.5) if pb > pa: imgi_norm[:, :, idim] = 255 * (imgdum - pa) / (pb - pa) # Save flow io.imsave(str(path_save / f'{file_name.stem}__flow__{obj_name}.png'), flowi) # Resize masks if necessary if new_size: mask_full = resize_mask(maski, sizes_orginal[idx]) io.imsave( str(path_save / f'{file_name.stem}__mask__{obj_name}.png'), mask_full) io.imsave( str(path_save / f'{file_name.stem}__mask_resize__{obj_name}.png'), maski) else: io.imsave( str(path_save / f'{file_name.stem}__mask__{obj_name}.png'), maski) # Save mask and flow images #f_mask = str(path_save / f'{file_name.stem}__mask__{obj_name}.png') #log_message(f'\nMask saved to file: {f_mask}\n', callback_fun=callback_log) #io.imsave(str(path_save / f'{file_name.stem}__mask__{obj_name}.png'), maski) # Save overview image fig = plt.figure(figsize=(12, 3)) plot.show_segmentation(fig, imgi_norm.astype('uint8'), maski, flowi) plt.tight_layout() fig.savefig(str(path_save / f'{file_name.stem}__seg__{obj_name}.png'), dpi=300) plt.close(fig) log_message( f"\nSegmentation of provided images finished ({(time.time() - start_time)}s)", callback_fun=callback_log)