Beispiel #1
0
def _merge_layers(input_dir, input_files, output_dir, output_file):
    zs = [z for z in input_files.keys()]  # sorted list of filenames by z-value
    zs.sort()

    # Initialize the output file
    br = BioReader(
        str(Path(input_dir).joinpath(input_files[zs[0]][0]).absolute()))
    bw = BioWriter(str(Path(output_dir).joinpath(output_file).absolute()),
                   metadata=br.read_metadata())
    bw.num_z(Z=len(zs))
    del br

    # Load each image and save to the volume file
    for z, i in zip(zs, range(len(zs))):
        br = BioReader(
            str(Path(input_dir).joinpath(input_files[z][0]).absolute()))
        bw.write_image(br.read_image(), Z=[i, i + 1])
        del br

    # Close the output image and delete
    bw.close_image()
    del bw
Beispiel #2
0
        {% endfor -%}
        {% for inp,val in cookiecutter._inputs|dictsort -%}
        {% for out,n in cookiecutter._outputs|dictsort -%}
        {% if val.type=="collection" and cookiecutter.use_bfio -%}
        # Loop through files in {{ inp }} image collection and process
        for i,f in enumerate({{ inp }}_files):
            # Load an image
            br = BioReader(Path({{ inp }}).joinpath(f))
            image = np.squeeze(br.read_image())

            # initialize the output
            out_image = np.zeros(image.shape,dtype=br._pix['type'])

            """ Do some math and science - you should replace this """
            logger.info('Processing image ({}/{}): {}'.format(i,len({{ inp }}_files),f))
            out_image = awesome_math_and_science_function(image)

            # Write the output
            bw = BioWriter(Path({{ out }}).joinpath(f),metadata=br.read_metadata())
            bw.write_image(np.reshape(out_image,(br.num_y(),br.num_x(),br.num_z(),1,1)))
        {%- endif %}{% endfor %}{% endfor %}
        
    finally:
        {%- if cookiecutter.use_bfio %}
        # Close the javabridge regardless of successful completion
        logger.info('Closing the javabridge')
        jutil.kill_vm()
        {%- endif %}
        
        # Exit the program
        sys.exit()
Beispiel #3
0
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()
Beispiel #4
0
        out_dict['r'] = R
    if 't' in variables:
        out_dict['t'] = T
    if 'c' in variables:
        out_dict['c'] = C
    base_output = output_name(inp_regex,
                              [i for i in test.get_matching(R=R, T=T, C=C)],
                              out_dict)

    # Export the flatfield image as a tiled tiff
    flatfield_out = base_output.replace('.ome.tif', '_flatfield.ome.tif')
    bw = BioWriter(str(output_dir.joinpath(flatfield_out)))
    bw.pixel_type('float')
    bw.num_x(X)
    bw.num_y(Y)
    bw.write_image(np.reshape(flatfield, (Y, X, 1, 1, 1)))
    bw.close_image()

    # Export the darkfield image as a tiled tiff
    if new_options['darkfield']:
        darkfield_out = base_output.replace('.ome.tif', '_darkfield.ome.tif')
        bw = BioWriter(str(output_dir.joinpath(darkfield_out)))
        bw.pixel_type('float')
        bw.num_x(X)
        bw.num_y(Y)
        bw.write_image(np.reshape(darkfield, (Y, X, 1, 1, 1)))
        bw.close_image()

    # Export the photobleaching components as csv
    if get_photobleach:
        offsets_out = base_output.replace('.ome.tif', '_offsets.csv')
Beispiel #5
0
     dark_image = np.zeros(flat_image.shape, dtype=np.float32)
 if photobleach != None:
     with open(photobleach, 'r') as f:
         reader = csv.reader(f)
         photo_offset = {
             line[0]: float(line[1])
             for line in reader if line[0] != 'file'
         }
     offset = np.mean([o for o in photo_offset.values()])
 ''' Apply flatfield to images '''
 for f in images.iterate(R=R, C=C, T=T):
     p = Path(f[0]['file'])
     logger.info("Applying flatfield to image: {}".format(p.name))
     br = BioReader(str(p.absolute()))
     image = br.read_image()
     if photobleach != None:
         new_image = _unshade(np.squeeze(image),
                              flat_image,
                              dark_image,
                              photo_offset[p.name],
                              offset=offset)
     else:
         new_image = _unshade(np.squeeze(image), flat_image, dark_image)
     bw = BioWriter(str(Path(outDir).joinpath(p.name).absolute()),
                    metadata=br.read_metadata())
     bw.write_image(np.reshape(new_image, image.shape))
     bw.close_image()
     del br
 ''' Close the javabridge '''
 logger.info("Closing the javabridge and ending process...")
 jutil.kill_vm()