def write_ome_tiffs(file_path, out_path): if Path(file_path).suffix != '.czi': TypeError("Path must be to a czi file.") base_name = Path(Path(file_path).name).stem czi = czifile.CziFile(file_path, detectmosaic=False) subblocks = [ s for s in czi.filtered_subblock_directory if s.mosaic_index is not None ] metadata_str = czi.metadata(True) metadata = czi.metadata(False)['ImageDocument']['Metadata'] chan_name = _get_channel_names(metadata) pix_size = _get_physical_dimensions(metadata_str) ind = {'X': [], 'Y': [], 'Z': [], 'C': [], 'T': [], 'Row': [], 'Col': []} for s in subblocks: scene = [ dim.start for dim in s.dimension_entries if dim.dimension == 'S' ] if scene is not None and scene[0] != 0: continue for dim in s.dimension_entries: if dim.dimension == 'X': ind['X'].append(dim.start) elif dim.dimension == 'Y': ind['Y'].append(dim.start) elif dim.dimension == 'Z': ind['Z'].append(dim.start) elif dim.dimension == 'C': ind['C'].append(dim.start) elif dim.dimension == 'T': ind['T'].append(dim.start) row_conv = { y: row for (y, row) in zip(np.unique(np.sort(ind['Y'])), range(0, len(np.unique(ind['Y'])))) } col_conv = { x: col for (x, col) in zip(np.unique(np.sort(ind['X'])), range(0, len(np.unique(ind['X'])))) } ind['Row'] = [row_conv[y] for y in ind['Y']] ind['Col'] = [col_conv[x] for x in ind['X']] for s, i in zip(subblocks, range(0, len(subblocks))): dims = [ _get_image_dim(s, 'Y'), _get_image_dim(s, 'X'), _get_image_dim(s, 'Z'), _get_image_dim(s, 'C'), _get_image_dim(s, 'T') ] data = s.data_segment().data().reshape(dims) Z = None if len(ind['Z']) == 0 else ind['Z'][i] C = None if len(ind['C']) == 0 else ind['C'][i] T = None if len(ind['T']) == 0 else ind['T'][i] out_file_path = os.path.join( out_path, _get_image_name(base_name, row=ind['Row'][i], col=ind['Col'][i], Z=Z, C=C, T=T)) bw = BioWriter(out_file_path, data) bw.channel_names([chan_name[C]]) bw.physical_size_x(pix_size['X'], 'µm') bw.physical_size_y(pix_size['Y'], 'µm') if pix_size['Z'] is not None: bw.physical_size_y(pix_size['Z'], 'µm') bw.write_image(data) bw.close_image()
def main(inpDir: Path, outDir: Path, filePattern: str = None) -> None: """ Turn labels into flow fields. Args: inpDir: Path to the input directory outDir: Path to the output directory """ # Use a gpu if it's available use_gpu = torch.cuda.is_available() if use_gpu: dev = torch.device("cuda") else: dev = torch.device("cpu") logger.info(f'Running on: {dev}') # Determine the number of threads to run on num_threads = max([cpu_count() // 2, 1]) logger.info(f'Number of threads: {num_threads}') # Get all file names in inpDir image collection based on input pattern if filePattern: fp = filepattern.FilePattern(inpDir, filePattern) inpDir_files = [file[0]['file'].name for file in fp()] logger.info('Processing %d labels based on filepattern ' % (len(inpDir_files))) else: inpDir_files = [f.name for f in Path(inpDir).iterdir() if f.is_file()] # Loop through files in inpDir image collection and process processes = [] if use_gpu: executor = ThreadPoolExecutor(num_threads) else: executor = ProcessPoolExecutor(num_threads) for f in inpDir_files: br = BioReader(Path(inpDir).joinpath(f).absolute()) out_file = Path(outDir).joinpath( f.replace('.ome', '_flow.ome').replace('.tif', '.zarr')).absolute() bw = BioWriter(out_file, metadata=br.metadata) bw.C = 4 bw.dtype = np.float32 bw.channel_names = ['cell_probability', 'x', 'y', 'labels'] bw._backend._init_writer() for z in range(br.Z): for x in range(0, br.X, TILE_SIZE): for y in range(0, br.Y, TILE_SIZE): processes.append( executor.submit(flow_thread, Path(inpDir).joinpath(f).absolute(), out_file, use_gpu, dev, x, y, z)) bw.close() br.close() done, not_done = wait(processes, 0) logger.info(f'Percent complete: {100 * len(done) / len(processes):6.3f}%') while len(not_done) > 0: for r in done: r.result() done, not_done = wait(processes, 5) logger.info( f'Percent complete: {100 * len(done) / len(processes):6.3f}%') executor.shutdown()