@@ -638,30 +638,34 @@ def save_to_png(images, masks, flows, file_names):
638638 save_masks (images , masks , flows , file_names , png = True )
639639
640640
641- def save_rois (masks , file_name , multiprocessing = None ):
641+ def save_rois (masks , file_name , multiprocessing = None , prefix = '' , pad = False ):
642642 """ save masks to .roi files in .zip archive for ImageJ/Fiji
643+ When opened in ImageJ, the ROIs will be named [prefix][0000]n where n is 1,2,... corresponding to the masks label
643644
644645 Args:
645646 masks (np.ndarray): masks output from Cellpose.eval, where 0=NO masks; 1,2,...=mask labels
646647 file_name (str): name to save the .zip file to
648+ multiprocessing (bool, optional): Flag to enable multiprocessing. Defaults to None (disabled).
649+ prefix (str, optional): prefix to add at the beginning of the ROI labels in ImageJ. Defaults to no prefix
650+ pad (bool, optional): Whether to pad the numerical part of the label with zeros so that all labels have the same length
647651
648652 Returns:
649653 None
650654 """
651655 outlines = utils .outlines_list (masks , multiprocessing = multiprocessing )
652- nonempty_outlines = [outline for outline in outlines if len (outline )!= 0 ]
653- if len (outlines )!= len (nonempty_outlines ):
654- print (f"empty outlines found, saving { len (nonempty_outlines )} ImageJ ROIs to .zip archive." )
655- rois = [ImagejRoi .frompoints (outline ) for outline in nonempty_outlines ]
656- file_name = os .path .splitext (file_name )[0 ] + '_rois.zip'
657-
656+
657+ n_digits = int (np .floor (np .log10 (masks .max ()))+ 1 ) if pad else 0
658+ fmt = f'{{prefix}}{{id:0{ n_digits } d}}'
659+ rois = []
660+ for n ,outline in zip (np .unique (masks )[1 :], outlines ):
661+ if len (outline ) > 0 :
662+ rois .append (ImagejRoi .frompoints (outline , name = fmt .format (prefix = prefix , id = n )))
658663
659- # Delete file if it exists; the roifile lib appends to existing zip files.
660- # If the user removed a mask it will still be in the zip file
661- if os .path .exists (file_name ):
662- os .remove (file_name )
664+ if len (outlines ) != len (rois ):
665+ print (f"empty outlines found, saving { len (rois )} ImageJ ROIs to .zip archive." )
663666
664- roiwrite (file_name , rois )
667+ file_name = os .path .splitext (file_name )[0 ] + '_rois.zip'
668+ roiwrite (file_name , rois , mode = 'w' )
665669
666670
667671def save_masks (images , masks , flows , file_names , png = True , tif = False , channels = [0 , 0 ],
0 commit comments