Example #1
0
def main(name, dst_name, ch_name, inference):
    path = find_dataset_dir(name)
    logger.info(f'loading original data from "{path}"')
    ds = SPIMDataset(path)

    if ch_name is None:
        ch_name = list(ds.keys())[0]
        logger.warning(f'channel not specified, using "{ch_name}"')

    ds = ds[ch_name]

    if not inference:
        # train...
        logger.info('start training N2V model')
        train(ds, name=name)
    else:
        logger.debug('... inference-only')

    # create output directory
    try:
        parent, _ = os.path.split(path)
        dst_dir = os.path.join(parent, dst_name)
        os.makedirs(dst_dir)
    except FileExistsError:
        pass

    # ... predict
    logger.info(f'start inference using N2V model ({name})')
    for name, result in zip(ds.keys(), predict(name, ds)):
        print(name)
        result_path = os.path.join(dst_dir, f'{name}.tif')
        imageio.volwrite(result_path, result)
Example #2
0
def save_segmentation_contour_overlay(im_fn, seg_fn, output_fn):
    """
    Write outline of contours to images and save to disk

    Parameters
    ----------
    im_fns : list
        list of filenames pointing to image files.
    seg_fns : list
        list of filenames pointing to segmentations, in the same order as im_fns.
    output_fns : list
        list of filenames to save, in the same order as the other inputs.
        Should have the .tif suffix, and will override any other.

    Returns
    -------
    None.

    """
    try:
        n = nibabel.load(im_fn)
        im = n.get_fdata().copy()
        seg = nibabel.load(seg_fn).get_fdata()
        if output_fn[-4:] not in ['.tif']:
            output_fn = output_fn + '.tif'
        #im = iu.apply_window(im, (300,80), unit_range=True)
        out = iu.draw_object_contours_3d(im, seg, window_level=(300, 80))
        out = np.moveaxis(out, 2, 0)
        out = (out / out.max() * 255).astype(np.int8)
        imageio.volwrite(output_fn, out)
        #export_tools.save_image_stack(out, output_fn)
        logger.debug('Saved contour overlays as {output_fn}')
    except FileNotFoundError as e:
        logger.error(
            f'Failed to parse {im_fn}, {seg_fn}, giving up due to error {e}')
Example #3
0
def main():
    ds = FolderDatastore("fusion_psf",
                         read_func=imageio.volread,
                         extensions=["tif"])
    logger.info(f"{len(ds)} file(s) found")

    # sandbox = Sandbox(ds)

    ratio = (2, 8, 8)
    sampler = tuple([slice(None, None, r) for r in ratio])

    overlap = 0.5

    tiles = list(ds.keys())
    for ref_key in tiles[:-1]:
        logger.debug(f".. loading {ref_key}")
        ref_im = ds[ref_key]
        # ref_im = ref_im[:, 1, :, :]
        ref_im_lo = ref_im[sampler]
        imageio.volwrite("ref_lo.tif", ref_im_lo)  # DEBUG
        print(ref_im_lo.shape)

        for tar_key in tiles[1:]:
            logger.info(f"{ref_key} -> {tar_key}")

            logger.debug(f".. loading {tar_key}")
            tar_im = ds[tar_key]
            # tar_im = tar_im[:, 1, :, :]
            tar_im_lo = tar_im[sampler]
            imageio.volwrite("tar_lo.tif", tar_im_lo)  # DEBUG

            pc = PhaseCorrelation(ref_im_lo, tar_im_lo)
            pc.run()
Example #4
0
def save_tif(data, path, fiji_executable, resolution):
    script_root = os.path.split(__file__)[0]
    # write initial tif with imageio
    if data.ndim == 3:
        n_slices = data.shape[0]
        imageio.volwrite(path, data)
        script = os.path.join(script_root, 'set_voxel_size_3d.ijm')

        # encode the arguments for the imagej macro:
        arguments = "%s,%i,%f,%f,%f" % (os.path.abspath(path), n_slices,
                                        resolution[0], resolution[1],
                                        resolution[2])
    else:
        n_channels = data.shape[0]
        n_slices = data.shape[1]
        imageio.mvolwrite(path, data)
        script = os.path.join(script_root, 'set_voxel_size_4d.ijm')

        # encode the arguments for the imagej macro:
        arguments = "%s,%i,%i,%f,%f,%f" % (os.path.abspath(path), n_slices,
                                           n_channels, resolution[0],
                                           resolution[1], resolution[2])

    # imagej macros can only take a single string as argument, so we need
    # to comma seperate the individual arguments
    assert "," not in path, "Can't encode pathname containing a comma"

    # call the imagej macro
    cmd = [fiji_executable, '-batch', '--headless', script, arguments]
    subprocess.run(cmd)
def write_logpack(fn, data):
    scale = max(np.log2(np.max(data)), -np.log2(np.min(data)))
    scale = int(np.ceil(100 * scale)) / 100.0
    idata = np.uint16((1 + np.log2(data) / scale) * 2**15)

    imageio.volwrite(fn + '_lp' + str(scale) + '.tif', idata)
    return scale
Example #6
0
def analyze_psf(ctx, path, ratio, lateral, axial, preview, save_roi,
                no_fix_negative):
    path = os.path.abspath(path)

    data = imageio.volread(path)
    if not no_fix_negative:
        vmin = np.min(data)
        if vmin < 0:
            data -= vmin

    analyzer = PSFAverage((axial, lateral, lateral), ratio)
    rois, table = analyzer(data)

    out_dir, _ = os.path.splitext(path)
    out_dir = f'{out_dir}_psf'
    try:
        os.mkdir(out_dir)
    except FileExistsError:
        logger.warning(f'output directory "{out_dir}" exists')

    if save_roi:
        logger.info("saving ROIs...")
        for i, roi in enumerate(rois):
            out_path = os.path.join(out_dir, f'psf_{i:03d}.tif')
            imageio.volwrite(out_path, roi)

    if preview:
        fig, ax = plt.subplots()
        plt.ion()
        plt.show()
Example #7
0
def main(image_path, psf_path):
    image = imageio.volread(image_path)  # z 0.6u
    psf = imageio.volread(psf_path)  # z 0.2u

    image, psf = image.astype(np.float32), psf.astype(np.float32)

    # crop image (too large)
    image = image[:, 768:768 + 512, 768:768 + 512]

    imageio.volwrite("input.tif", image)
    raise RuntimeError("DEBUG")

    # rescale psf
    psf = rescale(psf, (1 / 3, 1, 1), anti_aliasing=False)
    # normalize
    psf = (psf - psf.max()) / (psf.max() - psf.min())
    psf /= psf.sum()
    print(f"psf range [{psf.min(), psf.max()}]")

    print(f"image shape {image.shape}, psf shape {psf.shape}")

    try:
        deconv = deconvlucy(image, psf, 10)
    except Exception:
        raise
    else:
        print("saving...")
        imageio.volwrite("result.tif", deconv)
Example #8
0
def make_test_data():
    d = skimage.data.astronaut()
    d = d.transpose((2, 0, 1))
    d = np.concatenate(2 * [d], axis=0)
    d = d.astype('float32')
    d *= (np.iinfo('uint16').max / np.iinfo('uint8').max)
    d = d.astype('uint16')
    imageio.volwrite('../data/example.tif', d)
Example #9
0
 def writer(f, arr):
     if arr.ndim == 2:
         imwrite(f, arr, format="tiff")
     elif arr.ndim == 3:
         volwrite(f, arr, format="tiff")
     else:
         raise ValueError("cannot handle {}-dimensional data.".format(
             arr.ndim))
Example #10
0
def save_tif_stack(raw, save_file):
    try:
        imageio.volwrite(save_file, raw)
        return True
    except RuntimeError:
        print("Could not save tif stack, saving slices to folder %s instead" %
              save_file)
        save_tif_slices(raw, save_file)
def main(psf_path):
    data = imageio.volread(psf_path)

    # re-center the data
    cz, cy, cx = np.unravel_index(np.argmax(data), shape=data.shape)
    nz, ny, nx = data.shape

    data = [
        data[cz - 20, ...],
        data[cz - 15, ...],
        data[cz - 10, ...],
        data[cz - 5, ...],
        data[cz, ...],
        data[cz + 5, ...],
        data[cz + 10, ...],
        data[cz + 15, ...],
        data[cz + 20, ...],
    ]  # 200 per layer, 2 layer each
    data = np.array(data)

    # prep data
    data_prepped = prep_data_for_PR(data, 256)

    # set up model params
    params = dict(wl=520, na=1.05, ni=1.33, res=102, zres=1000)

    # retrieve the phase
    pr_start = time.time()
    print("Starting phase retrieval ... ", end="", flush=True)
    pr_result = retrieve_phase(data_prepped, params, max_iters=100)
    pr_time = time.time() - pr_start
    print(
        f"{pr_time:.1f} seconds were required to retrieve the pupil function")

    # plot
    pr_result.plot()
    pr_result.plot_convergence()

    # fit to zernikes
    zd_start = time.time()
    print("Starting zernike decomposition ... ", end="", flush=True)
    pr_result.fit_to_zernikes(120)
    zd_time = time.time() - zd_start
    print(f"{zd_time:.1f} seconds were required to fit 120 Zernikes")

    # plot
    pr_result.zd_result.plot_named_coefs()
    pr_result.zd_result.plot_coefs()

    plt.show()

    # save as tiff
    print("Write back...")
    zrange = np.linspace(-(nz - 1) // 2, (nz - 1) // 2, nz)
    zrange *= 200
    psf = pr_result.generate_psf(size=nx, zsize=200, zrange=zrange)

    imageio.volwrite("psf_hanser_pr.tif", psf.astype(np.float32))
Example #12
0
 def subtractBG(self, files):
     for f in files:
         img = imageio.volread(f)
         mode = scipy.stats.mode(img, axis=None)
         img = img.astype(np.float32)
         img = img - mode.mode
         img[img < 0] = 0
         img = img.astype(np.uint16)
         imageio.volwrite(f, img)
Example #13
0
def _SaveKer(ker, file, fold=FOLD_TMP, *, fmt=FMT.TIF):
    """
	Writes the 4D array `ker` [T,Z,Y,X] to a multilayer .tif image
	"""
    # Reorganize to maximize I/O speed #
    ker_ = np.moveaxis(ker, (0, 1), (3, 2))

    ## Write to File ##
    imageio.volwrite(fold + file + str(fmt), ker_)
Example #14
0
    def setUp(self):
        os.makedirs(self.slice_dir)
        self.data = np.random.randint(0, 128, dtype='uint8', size=self.shape)
        for z in range(self.data.shape[0]):
            name = 'z%03i.tiff' % z
            path = os.path.join(self.slice_dir, name)
            imageio.imwrite(path, self.data[z])

        imageio.volwrite(self.stack_path, self.data)
Example #15
0
        def save_movie(tracks, save_file):
            '''
            save movie with tracks
            '''

            track_data_framed=track_to_frame(tracks)

            final_img_set = np.zeros((self.movie_processed.shape[0], self.movie_processed.shape[1], self.movie_processed.shape[2], 3))

            for frameN in range(0, self.movie_processed.shape[0]):

                plot_info=track_data_framed['frames'][frameN]['tracks']
                frame_img=self.movie_processed[frameN,:,:]
                # Make a colour image frame
                orig_frame = np.zeros((self.movie_processed.shape[1], self.movie_processed.shape[2], 3))

                orig_frame [:,:,0] = frame_img/np.max(frame_img)*256
                orig_frame [:,:,1] = frame_img/np.max(frame_img)*256
                orig_frame [:,:,2] = frame_img/np.max(frame_img)*256

                for p in plot_info:
                    trace=p['trace']
                    trackID=p['trackID']

                    clr = trackID % len(self.color_list)
                    if (len(trace) > 1):
                        for j in range(len(trace)-1):
                            # Draw trace line
                            point1=trace[j]
                            point2=trace[j+1]
                            x1 = int(point1[1])
                            y1 = int(point1[0])
                            x2 = int(point2[1])
                            y2 = int(point2[0])
                            cv2.line(orig_frame, (int(x1), int(y1)), (int(x2), int(y2)),
                                     self.color_list[clr], 2)

                # Display the resulting tracking frame
                cv2.imshow('Tracking', orig_frame)

                ################### to save #################
                final_img_set[frameN,:,:,:]=orig_frame


                    # save results

            final_img_set=final_img_set/np.max(final_img_set)*255
            final_img_set=final_img_set.astype('uint8')
            # skimage.io.imsave(save_file, final_img_set)
            if not(save_file.endswith(".tif") or save_file.endswith(".tiff")):
                save_file += ".tif"
            imageio.volwrite(save_file, final_img_set)
            cv2.destroyAllWindows()
Example #16
0
    def downsample(src_path, dst_path=None):
        if dst_path is None:
            fname = os.path.basename(src_path)
            dst_path = os.path.join(dst_dir, fname)

        # extract
        array = volread_da(src_path)
        # transform
        array = array[sampler]
        # load
        imageio.volwrite(dst_path, array)

        return dst_path
Example #17
0
    def save(self, filename):
        """Save the simulated movie.

        Parameters
        ----------
        filename : str
            Output volume filename. Must be a volume format supported by `imageio.volwrite`

        Note
        ----
        The volume will be converted to single precision float (`numpy.float32`)
        """
        assert hasattr(self, "movie"), "You must first run the simulation"
        io.volwrite(filename, self.movie.astype(np.float32))
Example #18
0
def register(registered_filename, registered_filepath, raw_filename,
             raw_filepath):
    image_stack = imageio.volread(raw_filepath + raw_filename)
    sr = StackReg(StackReg.RIGID_BODY)
    registered_data = sr.register_transform_stack(image_stack,
                                                  reference='first',
                                                  verbose=True)
    finished_file = np.uint8(registered_data)
    try:
        os.mkdir(registered_filepath)
        print('directory made, saving registered image:' + registered_filename)
    except:
        print('directory exists, saving registered image:' +
              registered_filename)
    imageio.volwrite(registered_filepath + '/' + registered_filename,
                     finished_file,
                     bigtiff=True)
Example #19
0
def write_tiff(uri, data):
    """
    Write TIFF.

    Args:
        uri (str): target path
        data (array-like): the data
    
    Returns:
        (Future)
    """
    import imageio

    print(f"write_back={uri}")
    imageio.volwrite(uri, data)

    return uri
def save_tif(data, out_path, resolution):
    # write initial tif with imageio
    out_path = out_path + '.tif'
    imageio.volwrite(out_path, data)

    # encode the arguments for the imagej macro:
    # imagej macros can only take a single string as argument, so we need
    # to comma seperate the individual arguments
    assert "," not in out_path, "Can't encode pathname containing a comma"
    arguments = "%s,%i,%f,%f,%f" % (out_path, data.shape[0], resolution[0],
                                    resolution[1], resolution[2])

    # call the imagej macro
    fiji_executable = "/g/almf/software/Fiji.app/ImageJ-linux64"
    script = "/g/arendt/EM_6dpf_segmentation/platy-browser-data/registration/9.9.9/scripts/registration_targets/set_voxel_size.ijm"
    cmd = [fiji_executable, '-batch', '--headless', script, arguments]
    subprocess.run(cmd)
def save_tif(data, out_path, resolution):
    # the courtesy of Constantin
    # write initial tif
    out_path = out_path + '.tif'
    imageio.volwrite(out_path, data.astype('float32'))
    # encode the arguments for the imagej macro:
    # imagej macros can only take a single string as argument, so we need
    # to comma seperate the individual arguments
    assert "," not in out_path, "Can't encode pathname containing a comma"
    arguments = "%s,%i,%f,%f,%f" % (out_path, data.shape[0],
                                    resolution[0], resolution[1], resolution[2])
    # call the imagej macro
    fiji_executable = shutil.which('ImageJ')
    assert fiji_executable, 'ImageJ not found, the tif volume will not be saved'
    script = os.path.join(os.path.dirname(__file__), "set_voxel_size.ijm")
    cmd = [fiji_executable, '-batch', '--headless', script, arguments]
    subprocess.run(cmd)
Example #22
0
def _write3d(x, path, bitdepth=8):
    """
    x : [depth, height, width, channels=1]
    """
    assert (bitdepth in [8, 16, 32])
    x = clamp(x, low=0, high=1)

    if bitdepth == 32:
        x = x.astype(np.float32)

    else:
        if bitdepth == 8:
            x = x * 255
            # x = (x + 1) * 127.5
            x = x.astype(np.uint8)
        else:
            x = x * 65535
            # x = (x + 1) * 65535. /2
            x = x.astype(np.uint16)

    imageio.volwrite(path, x[..., 0])
Example #23
0
def main(root="fusion_psf"):
    ds = FolderDatastore(root, read_func=imageio.volread, extensions=["tif"])
    logger.info(f"{len(ds)} file(s) found")

    for key, vol in ds.items():
        logger.info(key)

        dst_dir = os.path.join(root, key)
        try:
            os.mkdir(dst_dir)
        except:
            # folder exists
            pass

        psf_avg = PSFAverage((97, 97, 97))
        psfs = psf_avg(vol, return_coords=True)

        psf_average = None
        for i, (sample, coord) in enumerate(psfs):
            coord = [f"{c:04d}" for c in reversed(coord)]
            coord = "-".join(coord)
            fname = f"psf_{i:03d}_{coord}.tif"
            imageio.volwrite(os.path.join(dst_dir, fname), sample)

            try:
                psf_average = (psf_average + sample) / 2
            except TypeError:
                psf_average = sample

        import cupy as cp

        psf_average = cp.asarray(psf_average)
        from utoolbox.exposure import auto_contrast

        psf_average = auto_contrast(psf_average)
        psf_average = cp.asnumpy(psf_average)

        preview_volume(psf_average)

        break
Example #24
0
def _write3d(x, filename, scale_pixel_value=True):
    """
    Params:
        -x : [depth, height, width]
        -max_val : possible maximum pixel value (65535 for 16-bit or 255 for 8-bit)
    """
    min_val = np.min(x)
    max_val = np.max(x)
    if scale_pixel_value:
        x = x - np.min(x)
        x = x / np.max(x)
        #print('min: %.2f max: %.2f\n' % (np.min(x), np.max(x)))
        #x = x + 1.2  #[0, 2]
        x = x * (255. / 2.)
        x = x.astype(np.uint8)

    else:
        x = x.astype(np.float32)

    imageio.volwrite(filename, x)
    #stack = sitk.GetImageFromArray(x)
    #sitk.WriteImage(stack, filename)
    return max_val, min_val
Example #25
0
def _write3d(x, path, bitdepth=8):
    """
    x : [depth, height, width, channels=1]
    """
    assert (bitdepth in [8, 16, 32])
    max_ = np.max(x)

    if bitdepth == 32:
        x = x.astype(np.float32)

    else:
        x = _clip(x, 2)
        min_ = np.min(x)
        x = (x - min_) / (max_ - min_)

        if bitdepth == 8:
            x = x * 255
            x = x.astype(np.uint8)
        else:
            x = x * 65535
            x = x.astype(np.uint16)

    imageio.volwrite(path, x[..., 0])
Example #26
0
def _write3d(x, path, bitdepth=16, norm_max=True):
    """
    x : [depth, height, width, channels=1]
    """
    assert (bitdepth in [8, 16, 32])

    if bitdepth == 32:
        x = x.astype(np.float32)

    else:
        if norm_max:
            x = (x + 1) / 2

        x[:, :16, :16, :], x[:, -16:, -16:, :] = 0, 0  #suppress the corners
        x[:, -16:, :16, :], x[:, :16, -16:, :] = 0, 0

        if bitdepth == 8:
            x = x * 255
            x = x.astype(np.uint8)
        else:
            x = x * 65535
            x = x.astype(np.uint16)

    imageio.volwrite(path, x[..., 0])
Example #27
0
def main(src_dir, dst_dir, angle, spacing, rotate):
    ctx = create_some_context()
    ctx.push()

    transform = DeskewTransform(spacing, angle, rotate=rotate)

    if not dst_dir:
        suffix = '_deskew' if rotate else '_shear'
        dst_dir = os.path.abspath(src_dir) + suffix
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
        logger.info("\"{}\" created".format(dst_dir))

    try:
        ds = llsm.Dataset(src_dir, show_uri=True, refactor=False)
        for fname, I_in in ds.datastore:
            logger.debug("deskew \"{}\"".format(fname))
            I_out = transform(I_in)
            basename = os.path.basename(fname)
            imageio.volwrite(os.path.join(dst_dir, basename), I_out)
    except Exception as e:
        logger.error(e)

    cuda.Context.pop()
def subsegment_image(Parameters, ROIs, root_dir, sub_path):
    """
    Use this module to prepare the images to help create ground truths of the cells    
    """
    #Load parameters and prepare output folders
    channels = Parameters["jpeg_channels"]
    suffix = Parameters["suffix"]
    move_to_front = Parameters.get('move_to_front', False)
    ground_truths = Parameters.get("ground_truths", False)
    if ground_truths: ground_truth_suffix = Parameters["ground_truth_suffix"]
    black_masks = Parameters.get("black_masks", False)
    debug = Parameters.get("debug_mode", False)

    if debug: print(root_dir, sub_path)
    if debug: print("subSegmenting image.... :)")

    filepath = root_dir / sub_path
    sub_JPEG_dir = root_dir / 'Segmented_JPEGs' / sub_path.parent
    sub_cell_dir = root_dir / 'Segmented_Image' / sub_path.parent
    sub_gt_dir = root_dir / 'Segmented_Ground_Truth' / sub_path.parent
    sub_bm_dir = root_dir / 'Segmented_Black_Mask' / sub_path.parent

    for dirs in [sub_JPEG_dir, sub_gt_dir, sub_cell_dir, sub_bm_dir]:
        if (not os.path.isdir(dirs)):
            os.makedirs(dirs)

    #Import and preprocess the image for the JPEG
    reader = imageio.get_reader(str(filepath))
    images = []
    for channel in channels:
        img = open_channel(channel, reader, False)
        img = img / np.amax(img)
        img = img * 255
        img = img.astype('uint8')
        images.append(img)

    merged_img = np.dstack([images[0], images[1], images[2]])
    height, width, _ = merged_img.shape
    full_image = imageio.volread(str(filepath))

    #Rearrange the channels if you've requested to move the target channels to the front
    if move_to_front:
        for i, channel in enumerate(channels):
            if debug: print(f"swapping {i} with {channel}")
            full_image[i, :, :] = full_image[channel, :, :]

    #Read in the ground truth image if you've set ground_truths to True
    if ground_truths:
        gt_filepath = filepath.parent / filepath.name.replace(
            suffix, ground_truth_suffix)
        if debug: print("GT", gt_filepath)
        gt_img = imageio.imread(gt_filepath)
        gt_img *= 255

    if debug: print(ROIs)
    #Process each of the ROIs
    for i in range(len(ROIs)):
        x_min = max(0, int(ROIs.loc[i, 'xmin']))
        x_max = min(width, int(ROIs.loc[i, 'xmax']))
        y_min = max(0, int(ROIs.loc[i, 'ymin']))
        y_max = min(height, int(ROIs.loc[i, 'ymax']))

        subJPEGimage = merged_img[y_min:y_max, x_min:x_max, :]
        imageio.imwrite(
            str(sub_JPEG_dir / sub_path.name.replace(suffix, f'{i}.jpg')),
            subJPEGimage)

        subimage = full_image[:, y_min:y_max, x_min:x_max]
        imageio.volwrite(
            str(sub_cell_dir / sub_path.name.replace(suffix, f'{i}{suffix}')),
            subimage)

        if black_masks:
            subblackmask = np.zeros(subimage.shape[1:])
            imageio.imwrite(
                str(sub_bm_dir / sub_path.name.replace(suffix, f'{i}.png')),
                subblackmask)

        if debug:
            print(
                merged_img.shape,
                x_min,
                x_max,
                y_min,
                y_max,
                subJPEGimage.shape,
                subimage.shape,
            )

        if ground_truths:
            gt_subimage = gt_img[y_min:y_max, x_min:x_max].copy()
            if debug:
                print(
                    gt_img.shape,
                    x_min,
                    x_max,
                    y_min,
                    y_max,
                    gt_subimage.shape,
                )
            imageio.imwrite(
                str(sub_gt_dir / sub_path.name.replace(suffix, f'{i}.png')),
                gt_subimage)
    return (None)
synthetic_data = np.random.random(size=(num_r, num_c, num_z) +
                                  tile_2d_shape).astype(np.float32)

###################################################################################################
# Write as a series of 3D tiffs.
# -------------------------------------------------------------

import os, tempfile
from imageio import volread, volwrite

dir = tempfile.TemporaryDirectory()

for r in range(num_r):
    for c in range(num_c):
        volwrite(os.path.join(dir.name, f"r{r}_c{c}.tiff"), synthetic_data[r,
                                                                           c])

###################################################################################################
# Now build a FetchedTile and TileFetcher based on this data.
# -----------------------------------------------------------

import functools
from starfish.experiment.builder import FetchedTile, TileFetcher


# We use this to cache images across tiles.  To avoid reopening and decoding the TIFF file, we use a
# single-element cache that maps between file_path and the array data.
@functools.lru_cache(maxsize=1)
def cached_read_fn(file_path) -> np.ndarray:
    return volread(file_path, format="tiff")
Example #30
0
def test_tifffile_reading_writing():
    """ Test reading and saving tiff """
    
    need_internet()  # We keep a test image in the imageio-binary repo
    
    im2 = np.ones((10, 10, 3), np.uint8) * 2

    filename1 = os.path.join(test_dir, 'test_tiff.tiff')

    # One image
    imageio.imsave(filename1, im2)
    im = imageio.imread(filename1)
    ims = imageio.mimread(filename1)
    assert im.shape == im2.shape
    assert (im == im2).all()
    assert len(ims) == 1
    
    # Multiple images
    imageio.mimsave(filename1, [im2, im2, im2])
    im = imageio.imread(filename1)
    ims = imageio.mimread(filename1)
    assert im.shape == im2.shape
    assert (im == im2).all()  # note: this does not imply that the shape match!
    assert len(ims) == 3
    for i in range(3):
        assert ims[i].shape == im2.shape
        assert (ims[i] == im2).all()

    # Read all planes as one array - we call it a volume for clarity
    vol = imageio.volread(filename1)
    vols = imageio.mvolread(filename1)
    assert vol.shape == (3, ) + im2.shape
    assert len(vols) == 1 and vol.shape == vols[0].shape
    for i in range(3):
        assert (vol[i] == im2).all()
    
    # remote multipage rgb file
    filename2 = get_remote_file('images/multipage_rgb.tif')
    img = imageio.mimread(filename2)
    assert len(img) == 2
    assert img[0].shape == (3, 10, 10)

    # Mixed
    W = imageio.save(filename1)
    W.set_meta_data({'planarconfig': 'SEPARATE'})  # was "planar"
    assert W.format.name == 'TIFF'
    W.append_data(im2)
    W.append_data(im2)
    W.close()
    #
    R = imageio.read(filename1)
    assert R.format.name == 'TIFF'
    ims = list(R)  # == [im for im in R]
    assert (ims[0] == im2).all()
    # meta = R.get_meta_data()
    # assert meta['orientation'] == 'top_left'  # not there in later version
    # Fail
    raises(IndexError, R.get_data, -1)
    raises(IndexError, R.get_data, 3)
    
    # Ensure imread + imwrite works round trip
    filename3 = os.path.join(test_dir, 'test_tiff2.tiff')
    im1 = imageio.imread(filename1)
    imageio.imwrite(filename3, im1)
    im3 = imageio.imread(filename3)
    assert im1.ndim == 3
    assert im1.shape == im3.shape
    assert (im1 == im3).all()
    
    # Ensure imread + imwrite works round trip - volume like
    filename3 = os.path.join(test_dir, 'test_tiff2.tiff')
    im1 = imageio.volread(filename1)
    imageio.volwrite(filename3, im1)
    im3 = imageio.volread(filename3)
    assert im1.ndim == 4
    assert im1.shape == im3.shape
    assert (im1 == im3).all()

    # Read metadata
    md = imageio.get_reader(filename2).get_meta_data()
    assert md['is_imagej'] is None
    assert md['description'] == 'shape=(2,3,10,10)'
    assert md['description1'] == ''
    assert md['datetime'] == datetime.datetime(2015, 5, 9, 9, 8, 29)
    assert md['software'] == 'tifffile.py'

    # Write metadata
    dt = datetime.datetime(2018, 8, 6, 15, 35, 5)
    w = imageio.get_writer(filename1, software='testsoftware')
    w.append_data(np.zeros((10, 10)), meta={'description': 'test desc',
                                            'datetime': dt})
    w.close()
    r = imageio.get_reader(filename1)
    md = r.get_meta_data()
    assert 'datetime' in md
    assert md['datetime'] == dt
    assert 'software' in md
    assert md['software'] == 'testsoftware'
    assert 'description' in md
    assert md['description'] == 'test desc'
coloredlogs.install(level="DEBUG",
                    fmt="%(asctime)s %(levelname)s %(message)s",
                    datefmt="%H:%M:%S")
##
# endregion
##

root = (
    "/Users/Andy/Documents/Sinica (Data)/Projects/ExM SIM/20181224_Expan_Tub_Tiling_SIM"
)

ds = ImageFolderDatastore(root, imageio.volread, pattern="RAWcell1_*")
n_phases = 5

root = os.path.join(root, "widefield")
try:
    os.mkdir(root)
except:
    pass
for fn, I in ds.items():
    logger.info('merging "{}"'.format(fn))
    nz, _, _ = I.shape
    J = []
    for iz in range(0, nz, n_phases):
        j = np.sum(I[iz:iz + 5, ...], axis=0, dtype=I.dtype)
        J.append(j)

    new_path = os.path.join(root, fn)
    imageio.volwrite(new_path, np.stack(J, axis=0))