Example #1
0
def main():
    """
    This demo converts a selected TIFF image to an APR, writes the result to file and then reads the file.
    """

    io_int = pyapr.filegui.InteractiveIO()

    # Read in an image
    fpath = io_int.get_tiff_file_name()
    img = skio.imread(fpath).astype(np.uint16)

    # Instantiate objects
    apr = pyapr.APR()
    parts = pyapr.ShortParticles()
    par = pyapr.APRParameters()
    converter = pyapr.converter.ShortConverter()

    # Set some parameters
    par.auto_parameters = False
    par.rel_error = 0.1
    par.Ip_th = 10
    par.grad_th = 1
    par.gradient_smoothing = 2
    par.sigma_th = 20
    par.sigma_th_max = 10
    converter.set_parameters(par)
    converter.set_verbose(False)

    # Compute APR and sample particle values
    converter.get_apr(apr, img)
    parts.sample_image(apr, img)

    # Compute and display the computational ratio
    numParts = apr.total_number_particles()
    numPix = img.size
    cr = numPix / numParts
    print(
        'Input image size: {} pixels, APR size: {} particles --> Computational Ratio: {}'
        .format(numPix, numParts, cr))

    # Save the APR to file
    fpath_apr = io_int.save_apr_file_name()  # get save path from gui
    pyapr.io.write(fpath_apr, apr, parts)  # write apr and particles to file

    # Read the newly written file
    apr2 = pyapr.APR()
    parts2 = pyapr.ShortParticles()
    pyapr.io.read(fpath_apr, apr2, parts2)

    # check that particles are equal at a single, random index
    ri = np.random.randint(0, numParts - 1)
    assert parts[ri] == parts2[ri]

    # check some APR properties
    assert apr.total_number_particles() == apr2.total_number_particles()
    assert apr.level_max() == apr2.level_max()
    assert apr.level_min() == apr2.level_min()
Example #2
0
def find_parameters_interactive(image,
                                rel_error=0.1,
                                gradient_smoothing=0,
                                verbose=True,
                                params=None,
                                slider_decimals=1):

    # check that the image array is c-contiguous
    if not image.flags['C_CONTIGUOUS']:
        print(
            'WARNING: \'image\' argument given to find_parameters_interactive is not C-contiguous \n'
            'input image has been replaced with a C-contiguous copy of itself')
        image = np.ascontiguousarray(image)

    while image.ndim < 3:
        image = np.expand_dims(image, axis=0)

    # Initialize objects
    io_int = pyapr.filegui.InteractiveIO()
    apr = pyapr.APR()
    if params is None:
        par = pyapr.APRParameters()
        par.auto_parameters = False
        par.rel_error = rel_error
        par.gradient_smoothing = gradient_smoothing
    else:
        par = params

    if image.dtype == np.float32:
        converter = pyapr.converter.FloatConverter()
    elif image.dtype == np.uint16:
        converter = pyapr.converter.ShortConverter()
    # elif image.dtype in {'byte', 'uint8'}:  # currently not working
    #     converter = pyapr.converter.ByteConverter()
    else:
        errstr = 'pyapr.converter.find_parameters_interactive: input image dtype must be numpy.uint16 or numpy.float32, ' \
                 'but {} was given'.format(image.dtype)
        raise TypeError(errstr)

    converter.set_parameters(par)
    converter.set_verbose(verbose)

    # launch interactive APR converter
    par = io_int.find_parameters_interactive(converter,
                                             apr,
                                             image,
                                             slider_decimals=slider_decimals)

    if verbose:
        print("---------------------------------")
        print("Using the following parameters:")
        print("grad_th = {}, sigma_th = {}, Ip_th = {}".format(
            par.grad_th, par.sigma_th, par.Ip_th))
        print("---------------------------------")

    return par
def main():
    """
    Interactive APR conversion. Reads in a selected TIFF image for interactive setting of the parameters:
        Ip_th       (background intensity level)
        sigma_th    (local intensity scale threshold)
        grad_th     (gradient threshold)

    Use the sliders to control the adaptation. The red overlay shows (approximately) the regions that will be fully
    resolved (at pixel resolution).

    Once the parameters are set, the final steps of the conversion pipeline are applied to produce the APR and sample
    the particle intensities.

    Note: The effect of grad_th may hide the effect of the other thresholds. It is thus recommended to keep grad_th
    low while setting Ip_th and sigma_th, and then increasing grad_th.
    """

    # Read in an image
    io_int = pyapr.filegui.InteractiveIO()
    fpath = io_int.get_tiff_file_name()  # get image file path from gui (data type must be float32 or uint16)
    img = skio.imread(fpath)

    # Set some parameters (only Ip_th, grad_th and sigma_th are set interactively)
    par = pyapr.APRParameters()
    par.rel_error = 0.1              # relative error threshold
    par.gradient_smoothing = 3       # b-spline smoothing parameter for gradient estimation
    #                                  0 = no smoothing, higher = more smoothing
    par.dx = 1
    par.dy = 1                       # voxel size
    par.dz = 1

    # Compute APR and sample particle values
    apr, parts = pyapr.converter.get_apr_interactive(img, params=par, verbose=True, slider_decimals=1)

    # Display the APR
    pyapr.viewer.parts_viewer(apr, parts)

    # Write the resulting APR to file
    print("Writing APR to file ... \n")
    fpath_apr = io_int.save_apr_file_name()  # get path through gui
    pyapr.io.write(fpath_apr, apr, parts)

    if fpath_apr:
        # Display the size of the file
        file_sz = os.path.getsize(fpath_apr)
        print("APR File Size: {:7.2f} MB \n".format(file_sz * 1e-6))

        # Compute compression ratio
        mcr = os.path.getsize(fpath) / file_sz
        print("Memory Compression Ratio: {:7.2f}".format(mcr))
Example #4
0
    def setUp(self):
        self.this_dir = os.path.dirname(os.path.abspath(__file__))
        self.impath_3D = os.path.abspath(
            os.path.join(
                self.this_dir,
                '../../LibAPR/test/files/Apr/sphere_120/sphere_original.tif'))
        self.impath_2D = os.path.abspath(
            os.path.join(self.this_dir,
                         '../../LibAPR/test/files/Apr/sphere_2D/original.tif'))
        self.impath_1D = os.path.abspath(
            os.path.join(self.this_dir,
                         '../../LibAPR/test/files/Apr/sphere_1D/original.tif'))

        self.apr_parameters = pyapr.APRParameters()
        self.apr_parameters.sigma_th = 30
        self.apr_parameters.grad_th = 15
Example #5
0
    def setUp(self):
        self.data_dir = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'test_files')
        self.impath_3D = os.path.abspath(
            os.path.join(self.data_dir, 'sphere_original.tif'))
        self.impath_2D = os.path.abspath(
            os.path.join(self.data_dir, 'sphere_2D.tif'))
        self.impath_1D = os.path.abspath(
            os.path.join(self.data_dir, 'sphere_1D.tif'))

        self.apr_parameters = pyapr.APRParameters()
        self.apr_parameters.sigma_th = 75
        self.apr_parameters.grad_th = 40
        self.apr_parameters.Ip_th = 0
        self.apr_parameters.gradient_smoothing = 0
        self.apr_parameters.output_dir = self.data_dir + '/'
Example #6
0
def main():
    """
    This demo shows how to convert an image to an APR using a fixed set of parameters.
    """

    # Read in an image
    io_int = pyapr.filegui.InteractiveIO()
    fpath = io_int.get_tiff_file_name()  # get image file path from gui (data type must be float32 or uint16)
    img = skio.imread(fpath)

    # Set some parameters
    par = pyapr.APRParameters()
    par.rel_error = 0.1          # relative error threshold
    par.gradient_smoothing = 3   # b-spline smoothing parameter for gradient estimation
    #                              0 = no smoothing, higher = more smoothing
    par.dx = 1
    par.dy = 1                   # voxel size
    par.dz = 1
    # threshold parameters
    par.Ip_th = 0                # regions below this intensity are regarded as background
    par.grad_th = 3              # gradients below this value are set to 0
    par.sigma_th = 10            # the local intensity scale is clipped from below to this value
    par.auto_parameters = False  # if true, threshold parameters are set automatically based on histograms

    # Compute APR and sample particle values
    apr, parts = pyapr.converter.get_apr(img, params=par, verbose=True)

    # Compute computational ratio
    cr = img.size/apr.total_number_particles()
    print("Compuational Ratio: {:7.2f}".format(cr))

    # Display the APR
    pyapr.viewer.parts_viewer(apr, parts)

    # Write the resulting APR to file
    print("Writing APR to file ... \n")
    fpath_apr = io_int.save_apr_file_name()  # get path through gui
    pyapr.io.write(fpath_apr, apr, parts)

    if fpath_apr:
        # Display the size of the file
        file_sz = os.path.getsize(fpath_apr)
        print("APR File Size: {:7.2f} MB \n".format(file_sz * 1e-6))

        # Compute compression ratio
        mcr = os.path.getsize(fpath) / file_sz
        print("Memory Compression Ratio: {:7.2f}".format(mcr))
Example #7
0
def get_apr(image,
            rel_error=0.1,
            gradient_smoothing=2,
            verbose=True,
            params=None):

    # check that the image array is c-contiguous
    if not image.flags['C_CONTIGUOUS']:
        print(
            'WARNING: \'image\' argument given to get_apr is not C-contiguous \n'
            'input image has been replaced with a C-contiguous copy of itself')
        image = np.ascontiguousarray(image)

    # Initialize objects
    apr = pyapr.APR()

    if params is None:
        par = pyapr.APRParameters()
        par.auto_parameters = True
        par.rel_error = rel_error
        par.gradient_smoothing = gradient_smoothing
    else:
        par = params

    if image.dtype == np.float32:
        parts = pyapr.FloatParticles()
        converter = pyapr.converter.FloatConverter()
    elif image.dtype == np.uint16:
        parts = pyapr.ShortParticles()
        converter = pyapr.converter.ShortConverter()
    # elif image.dtype in {'byte', 'uint8'}:  # currently not working
    #     parts = pyapr.ByteParticles()
    #     converter = pyapr.converter.ByteConverter()
    else:
        errstr = 'pyapr.converter.get_apr: input image dtype must be numpy.uint16 or numpy.float32, ' \
                 'but {} was given'.format(image.dtype)
        raise TypeError(errstr)

    converter.set_parameters(par)
    converter.set_verbose(verbose)

    # Compute the APR and sample particles
    converter.get_apr(apr, image)
    parts.sample_image(apr, image)

    return apr, parts
Example #8
0
def main():
    """
    Interactive APR conversion of large images. Reads in a block of z-slices for interactive setting of the
    following parameters:
        Ip_th       (background intensity level)
        sigma_th    (local intensity scale threshold)
        grad_th     (gradient threshold)

    Use the sliders to control the adaptation. The red overlay shows (approximately) the regions that will be fully
    resolved (at pixel resolution).

    Once the parameters are set, the entire image is processed in overlapping blocks of z-slices. The size of the
    blocks, and the overlap, can be set in the code below to control the memory consumption.

    Note: The effect of grad_th may hide the effect of the other thresholds. It is thus recommended to keep grad_th
    low while setting Ip_th and sigma_th, and then increasing grad_th.
    """

    # Read in an image
    io_int = pyapr.filegui.InteractiveIO()
    fpath = io_int.get_tiff_file_name(
    )  # get image file path from gui (data type must be float32 or uint16)

    # Specify the z-range to be used to set the parameters
    z_start = 0
    z_end = 256

    # Read slice range into numpy array
    with tifffile.TiffFile(fpath) as tif:
        img = tif.asarray(key=slice(z_start, z_end))

    # Set some parameters (only Ip_th, grad_th and sigma_th are set interactively)
    par = pyapr.APRParameters()
    par.rel_error = 0.1  # relative error threshold
    par.gradient_smoothing = 3  # b-spline smoothing parameter for gradient estimation
    #                                  0 = no smoothing, higher = more smoothing
    par.dx = 1
    par.dy = 1  # voxel size
    par.dz = 1

    # Interactively set the threshold parameters using the partial image
    par = pyapr.converter.find_parameters_interactive(img,
                                                      params=par,
                                                      verbose=True,
                                                      slider_decimals=1)

    del img  # Parameters found, we don't need the partial image anymore

    # par.input_dir + par.input_image_name must be the path to the image file
    par.input_dir = ''
    par.input_image_name = fpath

    # Initialize the by-block converter
    converter = pyapr.converter.ShortConverterBatch()
    converter.set_parameters(par)
    converter.set_verbose(True)

    # Parameters controlling the memory usage
    converter.set_block_size(
        256
    )  # number of z-slices to process in each block during APR conversion
    converter.set_ghost_size(
        32)  # number of ghost slices to use on each side of the blocks
    block_size_sampling = 256  # block size for sampling of particle intensities
    ghost_size_sampling = 128  # ghost size for sampling of particle intensities

    # Compute the APR
    apr = pyapr.APR()
    success = converter.get_apr(apr)

    if success:
        cr = apr.computational_ratio()
        print(
            'APR Conversion successful! Computational ratio (#pixels / #particles) = {}'
            .format(cr))

        print('Sampling particle intensity values')
        parts = pyapr.ShortParticles()
        parts.sample_image_blocked(apr, fpath, block_size_sampling,
                                   ghost_size_sampling)
        print('Done!')

        # View the result in the by-slice viewer
        pyapr.viewer.parts_viewer(apr, parts)

        # Write the resulting APR to file
        print("Writing APR to file ... \n")
        fpath_apr = io_int.save_apr_file_name()  # get path through gui
        pyapr.io.write(fpath_apr, apr, parts)

        if fpath_apr:
            # Display the size of the file
            file_sz = os.path.getsize(fpath_apr)
            print("APR File Size: {:7.2f} MB \n".format(file_sz * 1e-6))

            # Compute compression ratio
            mcr = os.path.getsize(fpath) / file_sz
            print("Memory Compression Ratio: {:7.2f}".format(mcr))

    else:
        print('Something went wrong...')
def convert_to_apr_point_cloud(fpath_image, fpath_mask):

    img = skio.imread(fpath_image)
    mask = skio.imread(fpath_mask)

    while img.ndim < 3:
        img = np.expand_dims(img, axis=0)

    apr = pyapr.APR()
    parts = pyapr.ShortParticles()
    par = pyapr.APRParameters()
    converter = pyapr.converter.ShortConverter()

    # Initialize APRParameters (only Ip_th, grad_th and sigma_th are set manually)
    par.auto_parameters = False
    par.rel_error = 0.1
    par.gradient_smoothing = 2
    par.min_signal = 200
    par.noise_sd_estimate = 5

    #Setting the APRParameters (only Ip_th, grad_th and sigma_th) using the global values
    par.Ip_th = IP_TH
    par.grad_th = GRAD_TH
    par.sigma_th = SIGMA_TH

    converter.set_parameters(par)
    converter.set_verbose(True)

    # # Compute APR and sample particle values
    converter.get_apr(apr, img)
    parts.sample_image(apr, img)
    # apr, parts = pyapr.converter.get_apr_interactive(img, dtype=img.dtype, params=par, verbose=True)

    # Display the APR
    # pyapr.viewer.parts_viewer(apr, parts)

    # Converting APR into Pointcloud
    org_dims = apr.org_dims()  # (Ny, Nx, Nz)
    #py_recon = np.empty((org_dims[2], org_dims[1], org_dims[0]), dtype=np.uint16)
    max_level = apr.level_max()

    apr_it = apr.iterator()

    v_min = min(parts)
    v_max = max(parts)
    point = []
    for idx, part in enumerate(parts):
        parts[idx] = int(((parts[idx] - v_min) / (v_max - v_min)) * 255)

    # loop over levels up to level_max-1
    for level in range(apr_it.level_min(), apr_it.level_max() + 1):

        step_size = 2**(max_level - level)

        for z in range(apr_it.z_num(level)):
            for x in range(apr_it.x_num(level)):
                for idx in range(apr_it.begin(level, z, x), apr_it.end()):
                    y = apr_it.y(idx)  # this is slow

                    y_start = y * step_size
                    x_start = x * step_size
                    z_start = z * step_size

                    point += [[
                        x_start, y_start, z_start, parts[idx],
                        mask[z_start, x_start, y_start]
                    ]]

    point_cloud = np.array(point)

    # Write the resulting APR to file
    print("Writing Point Cloud to file ... \n")
    start_idx = 8
    if "_2" in fpath_image: start_idx = start_idx + 2
    fpath_pointcloud = "./data/APRPointCloud/test/" + fpath_image[
        -start_idx:-4] + ".txt"
    np.savetxt(fpath_pointcloud, point_cloud, delimiter=',')

    # # Initialize APRFile for I/O
    # aprfile = pyapr.io.APRFile()
    # aprfile.set_read_write_tree(True)

    # # Write APR and particles to file
    # aprfile.open(fpath_apr, 'WRITE')
    # aprfile.write_apr(apr)
    # aprfile.write_particles('particles', parts)

    # # Compute compression and computational ratios
    # file_sz = aprfile.current_file_size_MB()
    # print("APR File Size: {:7.2f} MB \n".format(file_sz))
    # print("Total number of particles: {}".format(apr.total_number_particles()))
    # mcr = os.path.getsize(fpath_image) * 1e-6 / file_sz
    # cr = img.size/apr.total_number_particles()

    # print("Memory Compression Ratio: {:7.2f}".format(mcr))
    # print("Compuational Ratio: {:7.2f}".format(cr))

    # aprfile.close()

    return 0
Example #10
0
def get_apr_interactive(image,
                        rel_error=0.1,
                        gradient_smoothing=2,
                        verbose=True,
                        params=None,
                        slider_decimals=1):

    # check that the image array is c-contiguous
    if not image.flags['C_CONTIGUOUS']:
        print(
            'WARNING: \'image\' argument given to get_apr_interactive is not C-contiguous \n'
            'input image has been replaced with a C-contiguous copy of itself')
        image = np.ascontiguousarray(image)

    while image.ndim < 3:
        image = np.expand_dims(image, axis=0)

    # Initialize objects
    io_int = pyapr.InteractiveIO()
    apr = pyapr.APR()

    if params is None:
        par = pyapr.APRParameters()
        par.auto_parameters = False
        par.rel_error = rel_error
        par.gradient_smoothing = gradient_smoothing
    else:
        par = params

    if image.dtype == np.float32:
        parts = pyapr.FloatParticles()
        converter = pyapr.converter.FloatConverter()
    elif image.dtype == np.uint16:
        parts = pyapr.ShortParticles()
        converter = pyapr.converter.ShortConverter()
    # elif image.dtype in {'byte', 'uint8'}:  # currently not working
    #     parts = pyapr.ByteParticles()
    #     converter = pyapr.converter.ByteConverter()
    else:
        errstr = 'pyapr.converter.get_apr_interactive: input image dtype must be numpy.uint16 or numpy.float32, ' \
                 'but {} was given'.format(image.dtype)
        raise TypeError(errstr)

    converter.set_parameters(par)
    converter.set_verbose(verbose)

    # launch interactive APR converter
    io_int.interactive_apr(converter,
                           apr,
                           image,
                           slider_decimals=slider_decimals)

    if verbose:
        print("Total number of particles: {}".format(
            apr.total_number_particles()))
        print("Number of pixels in original image: {}".format(image.size))
        cr = image.size / apr.total_number_particles()
        print("Compuational Ratio: {:7.2f}".format(cr))

    # sample particles
    parts.sample_image(apr, image)

    return apr, parts