Пример #1
0
def save_as_tiff(data, filename, resolution=(0.22, 0.22)):
    savefile = (data / np.max(data) * (2**16 - 1)).astype('uint16')
    with TiffWriter(filename + '.tif', imagej=True) as tif:
        for i in range(savefile.shape[0]):
            tif.save(np.squeeze(savefile[i]),
                     compress=0,
                     resolution=resolution)
Пример #2
0
def stkshow(images, fname='/home/rfor10/Downloads/tmp-stk.tif'):
    with TiffWriter(fname, bigtiff=False, imagej=True) as t:
        if len(images.shape) > 2:
            for i in range(images.shape[2]):
                t.save(images[:, :, i].astype('uint16'))
        else:
            t.save(images.astype('uint16'))
Пример #3
0
 def save_custom_mask(self, path, x_intercept_fraction=0.667):
     """
   Save a Tumor file 
   """
     _v = np.zeros((self.shape[0], self.shape[1], 4)).astype(np.uint8)
     span_range = int(_v.shape[1] * x_intercept_fraction)
     _v[:, :span_range, ] = (255, 221, 221, 255)
     with TiffWriter(path) as tif:
         tif.save(_v, compress=9)
Пример #4
0
 def save_component(self, path, frame_name):
     """
     Save a component image
     """
     with TiffWriter(path) as tif:
         for channel in self.components:
             tif.save(self.components[channel].astype(np.float32),
                      compress=9,
                      extratags=[(tif_tag_integer['ImageDescription'], 's',
                                  0, _get_description(channel,
                                                      frame_name), True)])
Пример #5
0
def convert_to_tif(f_name):
    read_file = h5py.File(f_name)
    base_data = read_file['DataSet']

    # THIS ASSUMES THAT YOU HAVE A MULTICOLOR Z STACK IN TIME
    resolution_levels, \
    time_points, n_time_points, \
    channels, n_channels, \
    n_z_levels, z_levels, \
    n_rows, n_cols = get_h5_file_info(base_data)

    # Get the index of the bad frame start
    bad_index_start = get_bad_frame_index(
        np.array(base_data[resolution_levels[0]][time_points[0]][channels[0]]
                 ['Data']))

    banner_text = 'File Breakdown'
    print(banner_text)
    print('_' * len(banner_text))
    print('Channels: %d' % n_channels)
    print('Time Points: %d' % n_time_points)
    print('Z Levels: %d' % (bad_index_start + 1))
    print('Native (rows, cols): (%d,%d)' % (n_rows, n_cols))
    print('_' * len(banner_text))

    with TiffWriter(f_name.rsplit('.', maxsplit=1)[0].split('/')[-1] + '.tif',
                    imagej=True) as out_tif:
        mmap_fname = f_name + '.mmap'
        output_stack = np.memmap(mmap_fname,
                                 dtype=np.uint16,
                                 shape=(n_time_points, bad_index_start,
                                        n_channels, n_rows, n_cols),
                                 mode='w+')

        for i_t, t in enumerate(time_points):
            print('%s/%d' % (t, n_time_points - 1))
            for i_z, z_lvl in enumerate(z_levels[:bad_index_start]):
                print('%s/%d Z %d/%d' %
                      (t, n_time_points - 1, i_z + 1, bad_index_start))
                for i_channel, channel in enumerate(channels):
                    output_stack[i_t, i_z, i_channel] = img_as_uint(
                        np.array(
                            base_data[resolution_levels[0]][time_points[i_t]][
                                channels[i_channel]]['Data'][i_z]))

        # Save the reduced file
        out_tif.save(output_stack)

        # Delete the reduced stack
        del output_stack
        os.remove(mmap_fname)
Пример #6
0
 def save_invasive_margin_mask(self,
                               path,
                               x_intercept_fraction=0.667,
                               width_pixels=10):
     """
   Save a Invsive Margin file 
   """
     _v = np.zeros((self.shape[0], self.shape[1], 4)).astype(np.uint8)
     span_range = int(_v.shape[1] * x_intercept_fraction)
     left_add = int(width_pixels / 2)
     right_add = width_pixels - left_add
     _v[:, span_range - left_add:span_range + right_add, ] = (255, 255, 255,
                                                              255)
     with TiffWriter(path) as tif:
         tif.save(_v, compress=9)
Пример #7
0
def write_tiffs(data, ops, k, ichan):
    if ichan==0:
        if ops['functional_chan']==ops['align_by_chan']:
            tifroot = os.path.join(ops['save_path'], 'reg_tif')
        else:
            tifroot = os.path.join(ops['save_path'], 'reg_tif_chan2')
    else:
        if ops['functional_chan']==ops['align_by_chan']:
            tifroot = os.path.join(ops['save_path'], 'reg_tif')
        else:
            tifroot = os.path.join(ops['save_path'], 'reg_tif_chan2')
    if not os.path.isdir(tifroot):
        os.makedirs(tifroot)
    fname = 'file_chan%0.3d.tif'%k
    with TiffWriter(os.path.join(tifroot, fname)) as tif:
        for i in range(data.shape[0]):
            tif.save(data[i])
Пример #8
0
def save_image(image, metadata, directory, file_name):
    '''
    Save Image. Metadata not saved currently!!
    '''

    if metadata["DimensionOrder"] == 'XYZCT':

        with TiffWriter(os.path.join(directory, file_name)) as tif:
            #for index, (i, j, k) in enumerate(product(range(metadata['SizeC']), range(metadata['SizeT']), range(metadata['SizeZ']))):
            for i, j, k in product(range(image.shape[0]),
                                   range(image.shape[1]),
                                   range(image.shape[2])):

                if i == 0 and j == 0 and k == 0:

                    tif.save(image[i][j][k],
                             description=metadata_to_ome(metadata, file_name))
                else:
                    tif.save(image[i][j][k])
    else:
        raise Exception('The dimension order has to be XYCZT!')
Пример #9
0
def save_image(image, metadata, directory, file_name):
    '''
    Save Image. Metadata not saved currently!!
    '''

    #if metadata["DimensionOrder"]!='XYCZT':
    #image.reorder('XYCZT')

    imagej_description, imagej_metadata = metadata_to_imageJ(metadata)

    print(image.shape)

    with TiffWriter(os.path.join(directory, file_name)) as tif:
        #for index, (i, j, k) in enumerate(product(range(metadata['SizeC']), range(metadata['SizeT']), range(metadata['SizeZ']))):
        for i, j, k in product(range(image.shape[0]), range(image.shape[1]),
                               range(image.shape[2])):
            if i == 0 and j == 0 and k == 0:
                tif.save(image[i][j][k],
                         description=imagej_description,
                         metadata=imagej_metadata)
            else:
                tif.save(image[i][j][k])
Пример #10
0
def write(data, ops, k, ichan):
    """ writes frames to tiffs

    Parameters
    ----------
    data : int16
        frames x Ly x Lx

    ops : dictionary
        requires 'functional_chan', 'align_by_chan'

    k : int
        number of tiff

    ichan : bool
        channel is ops['align_by_chan']

    """
    if ichan:
        if ops['functional_chan']==ops['align_by_chan']:
            tifroot = os.path.join(ops['save_path'], 'reg_tif')
            wchan = 0
        else:
            tifroot = os.path.join(ops['save_path'], 'reg_tif_chan2')
            wchan = 1
    else:
        if ops['functional_chan']==ops['align_by_chan']:
            tifroot = os.path.join(ops['save_path'], 'reg_tif_chan2')
            wchan = 1
        else:
            tifroot = os.path.join(ops['save_path'], 'reg_tif')
            wchan = 0
    if not os.path.isdir(tifroot):
        os.makedirs(tifroot)
    fname = 'file%0.3d_chan%d.tif'%(k,wchan)
    with TiffWriter(os.path.join(tifroot, fname)) as tif:
        for i in range(data.shape[0]):
            tif.save(data[i])
Пример #11
0
    def save_binary_seg_maps(self,
                             path,
                             processed_image=True,
                             regions=False,
                             x_intercept_fraction=0.667):
        """
        Save a binary_seg_map image based on the **.make_cell_image_()** images in a python-readable format
        """
        region_image = np.zeros((self.shape[0], self.shape[1])).astype(int)
        span_range = int(region_image.shape[1] * x_intercept_fraction)
        region_image[:, :span_range] = 1
        region_image[:, span_range:] = 2
        _region_xml = '''<?xml version="1.0" encoding="utf-16"?>\r\n<TissueClassMap>\r\n <Version>1</Version>\r\n <Entry>\r\n  <Name>Tumor</Name>\r\n  <Color>255,255,0,0</Color>\r\n  <ID>746136c0-5450-440a-aff7-0969f493f5e3</ID>\r\n </Entry>\r\n <Entry>\r\n  <Name>Stroma</Name>\r\n  <Color>255,0,255,0</Color>\r\n  <ID>6c77d103-7122-4239-b588-5287ddfd028f</ID>\r\n </Entry>\r\n</TissueClassMap>'''

        with TiffWriter(path) as tif:
            if regions:
                tif.save(region_image.astype(np.uint32),
                         compress=9,
                         extratags=[(tif_tag_integer['ImageDescription'], 's',
                                     0, _region_xml, True)])
            tif.save(self.nucleus_image.astype(np.uint32),
                     compress=9,
                     extratags=[(tif_tag_integer['ImageDescription'], 's', 0,
                                 _nuc_xml, True)])
            tif.save(self.edge_image.astype(np.uint32),
                     compress=9,
                     extratags=[(tif_tag_integer['ImageDescription'], 's', 0,
                                 _mem_xml, True)])
            if processed_image:
                tif.save(self.processed_image.astype(np.uint32),
                         compress=9,
                         extratags=[(tif_tag_integer['ImageDescription'], 's',
                                     0, _pro_xml, True)])
        if regions:
            return {1: 'Tumor', 2: 'Stroma'}, region_image.astype(np.uint32)
        return None, None
Пример #12
0
                                     for z in xrange(0, img_3d.shape[0])))
        pool.close()

        for z in xrange(0, img_3d.shape[0]):
            img_3d[z, :, :] = img_temp[z]

        stop = timeit.default_timer()
        print('Total time: {0}s'.format(stop - start))

        #write images

        print('Writing images...')

        start = timeit.default_timer()

        # for k in tqdm(xrange(img_3d.shape[0])):
        # 	#cv2.imwrite(data_name2+'\\'+file_name + '_' + str(k).zfill(6) +'.tif', img_3d[k,:,:])
        # 	tifffile.imsave(data_name2 + '\\' + str(k*3).zfill(6) + '.tiff', img_3d[k,:,:])

        with TiffWriter(data_name2 + '\\' + file_name + '.tif',
                        bigtiff=True) as tif:
            tif.save(img_3d)

        stop = timeit.default_timer()
        print('Total time: {0}s'.format(stop - start))

    libc.CloseDcimg()

    if args.delete:
        os.remove(file_path)
Пример #13
0
def downsample_to_tif(f_name, ds_factor=8):
    read_file = h5py.File(f_name)
    base_data = read_file['DataSet']

    # THIS ASSUMES THAT YOU HAVE A MULTICOLOR Z STACK IN TIME
    # f_name = askopenfilename(title='Choose File To Convert')
    # Hard-code the downsample factor to 8. Will make a different program for the
    # 1:1 conversion
    resolution_levels, \
    time_points, n_time_points, \
    channels, n_channels, \
    n_z_levels, z_levels, \
    n_rows, n_cols = get_h5_file_info(base_data)

    n_time_points = 3
    time_points = time_points[0:n_time_points]

    # Get the size of the downsampled image. Only going to downsample in x and y
    if ds_factor < 2:
        raise SystemExit('Downsample factor must be >=2')

    test_ds_frame = pyramid_reduce(np.array(base_data[resolution_levels[0]][
        time_points[0]][channels[0]]['Data'][0]),
                                   downscale=ds_factor)
    ds_n_rows, ds_n_cols = test_ds_frame.shape

    # Get the index of the bad frame start
    bad_index_start = get_bad_frame_index(
        np.array(base_data[resolution_levels[0]][time_points[0]][channels[0]]
                 ['Data']))

    banner_text = 'File Breakdown'
    print(banner_text)
    print('_' * len(banner_text))
    print('Channels: %d' % n_channels)
    print('Time Points: %d' % n_time_points)
    print('Z Levels: %d' % (bad_index_start + 1))
    print('Native (rows, cols): (%d,%d)' % (n_rows, n_cols))
    print('Downsampled (rows, cols): (%d,%d)' % (ds_n_rows, ds_n_cols))
    print('_' * len(banner_text))

    f_ending = '_downsampled_%dX.tif' % ds_factor

    with TiffWriter(f_name.rsplit('.', maxsplit=1)[0].split('/')[-1] +
                    f_ending,
                    imagej=True) as out_tif:
        output_stack = np.zeros(shape=(n_time_points, bad_index_start,
                                       n_channels, ds_n_rows, ds_n_cols),
                                dtype=np.uint16)

        for i_t, t in enumerate(time_points):
            print('%s/%d' % (t, n_time_points - 1))
            for i_z, z_lvl in enumerate(z_levels[:bad_index_start]):
                print('%s/%d Z %d/%d' %
                      (t, n_time_points - 1, i_z + 1, bad_index_start))
                for i_channel, channel in enumerate(channels):
                    output_stack[i_t, i_z, i_channel] = img_as_uint(
                        pyramid_reduce(img_as_float(
                            np.array(base_data[resolution_levels[0]][
                                time_points[i_t]][channels[i_channel]]['Data']
                                     [i_z])),
                                       downscale=ds_factor))

        out_tif.save(output_stack)
        del output_stack
Пример #14
0
def write(filename,
          image,
          sed=None,
          optical=None,
          ranges=None,
          multichannel=True,
          dtype=None,
          write_float=None):
    """Writes MIBI data to a multipage TIFF.

    Args:
        filename: The path to the target file if multi-channel, or the path to
            a folder if single-channel.
        image: A :class:`mibidata.mibi_image.MibiImage` instance.
        sed: Optional, an array of the SED image data. This is assumed to be
            grayscale even if 3-dimensional, in which case only one channel
            will be used.
        optical: Optional, an RGB array of the optical image data.
        ranges: A list of (min, max) tuples the same length as the number of
            channels. If None, the min will default to zero and the max to the
            max pixel value in that channel. This is used by some external
            software to calibrate the display.
        multichannel: Boolean for whether to create a single multi-channel TIFF,
            or a folder of single-channel TIFFs. Defaults to True; if False,
            the sed and optical options are ignored.
        dtype: dtype: One of (``np.float32``, ``np.uint16``) to force the dtype
            of the saved image data. Defaults to ``None``, which chooses the
            format based on the data's input type, and will convert to
            ``np.float32`` or ``np.uint16`` from other float or int types,
            respectively, if it can do so without a loss of data.
        write_float: Deprecated, will raise ValueError if specified. To
            specify the dtype of the saved image, please use the `dtype`
            argument instead.

    Raises:
        ValueError: Raised if

            * The image is not a :class:`mibidata.mibi_image.MibiImage`
              instance.
            * The :class:`mibidata.mibi_image.MibiImage` coordinates, size,
              fov_id, fov_name, run, folder, dwell, scans, mass_gain,
              mass_offset, time_resolution, masses or targets are None.
            * `dtype` is not one of ``np.float32`` or ``np.uint16``.
            * `write_float` has been specified.
            * Converting the native :class:`mibidata.mibi_image.MibiImage` dtype
              to the specified or inferred ``dtype`` results in a loss of data.
    """
    if not isinstance(image, mi.MibiImage):
        raise ValueError('image must be a mibidata.mibi_image.MibiImage '
                         'instance.')
    missing_required_metadata = [
        m for m in REQUIRED_METADATA_ATTRIBUTES if not getattr(image, m)
    ]
    if missing_required_metadata:
        if len(missing_required_metadata) == 1:
            missing_metadata_error = (f'{missing_required_metadata[0]} is '
                                      f'required and may not be None.')
        else:
            missing_metadata_error = (f'{", ".join(missing_required_metadata)}'
                                      f' are required and may not be None.')
        raise ValueError(missing_metadata_error)

    if write_float is not None:
        raise ValueError('`write_float` has been deprecated. Please use the '
                         '`dtype` argument instead.')
    if dtype and not dtype in [np.float32, np.uint16]:
        raise ValueError('Invalid dtype specification.')

    if dtype == np.float32:
        save_dtype = np.float32
        range_dtype = 'd'
    elif dtype == np.uint16:
        save_dtype = np.uint16
        range_dtype = 'I'
    elif np.issubdtype(image.data.dtype, np.floating):
        save_dtype = np.float32
        range_dtype = 'd'
    else:
        save_dtype = np.uint16
        range_dtype = 'I'

    to_save = image.data.astype(save_dtype)
    if not np.all(np.equal(to_save, image.data)):
        raise ValueError('Cannot convert data from '
                         f'{image.data.dtype} to {save_dtype}')

    if ranges is None:
        ranges = [(0, m) for m in to_save.max(axis=(0, 1))]

    coordinates = [
        (286, '2i', 1, _micron_to_cm(image.coordinates[0])),  # x-position
        (287, '2i', 1, _micron_to_cm(image.coordinates[1])),  # y-position
    ]
    resolution = (image.data.shape[0] * 1e4 / float(image.size),
                  image.data.shape[1] * 1e4 / float(image.size), 'cm')

    # The mibi. prefix is added to attributes defined in the spec.
    # Other user-defined attributes are included too but without the prefix.
    prefixed_attributes = mi.SPECIFIED_METADATA_ATTRIBUTES[1:]
    description = {}
    for key, value in image.metadata().items():
        if key in prefixed_attributes:
            description[f'mibi.{key}'] = value
        elif key in RESERVED_MIBITIFF_ATTRIBUTES:
            warnings.warn(f'Skipping writing user-defined {key} to the '
                          f'metadata as it is a reserved attribute.')
        elif key != 'date':
            description[key] = value
    # TODO: Decide if should filter out those that are None or convert to empty
    # string so that don't get saved as 'None'

    if multichannel:
        targets = list(image.targets)
        util.sort_channel_names(targets)
        indices = image.channel_inds(targets)
        with TiffWriter(filename, software=SOFTWARE_VERSION) as infile:
            for i in indices:
                metadata = description.copy()
                metadata.update({
                    'image.type': 'SIMS',
                    'channel.mass': int(image.masses[i]),
                    'channel.target': image.targets[i],
                })
                page_name = (285, 's', 0,
                             '{} ({})'.format(image.targets[i],
                                              image.masses[i]))
                min_value = (340, range_dtype, 1, ranges[i][0])
                max_value = (341, range_dtype, 1, ranges[i][1])
                page_tags = coordinates + [page_name, min_value, max_value]

                infile.save(to_save[:, :, i],
                            compress=6,
                            resolution=resolution,
                            extratags=page_tags,
                            metadata=metadata,
                            datetime=image.date)
            if sed is not None:
                if sed.ndim > 2:
                    sed = sed[:, :, 0]

                sed_resolution = (sed.shape[0] * 1e4 / float(image.size),
                                  sed.shape[1] * 1e4 / float(image.size), 'cm')

                page_name = (285, 's', 0, 'SED')
                page_tags = coordinates + [page_name]
                infile.save(sed,
                            compress=6,
                            resolution=sed_resolution,
                            extratags=page_tags,
                            metadata={'image.type': 'SED'})
            if optical is not None:
                infile.save(optical,
                            compress=6,
                            metadata={'image.type': 'Optical'})
                label_coordinates = (_TOP_LABEL_COORDINATES
                                     if image.coordinates[1] > 0 else
                                     _BOTTOM_LABEL_COORDINATES)
                slide_label = np.fliplr(
                    np.moveaxis(
                        optical[
                            label_coordinates[0][0]:label_coordinates[0][1],
                            label_coordinates[1][0]:label_coordinates[1][1]],
                        0, 1))
                infile.save(slide_label,
                            compress=6,
                            metadata={'image.type': 'Label'})

    else:
        for i in range(image.data.shape[2]):
            metadata = description.copy()
            metadata.update({
                'image.type': 'SIMS',
                'channel.mass': int(image.masses[i]),
                'channel.target': image.targets[i],
            })
            page_name = (285, 's', 0, '{} ({})'.format(image.targets[i],
                                                       image.masses[i]))
            min_value = (340, range_dtype, 1, ranges[i][0])
            max_value = (341, range_dtype, 1, ranges[i][1])
            page_tags = coordinates + [page_name, min_value, max_value]

            target_filename = os.path.join(
                filename,
                '{}.tiff'.format(util.format_for_filename(image.targets[i])))

            with TiffWriter(target_filename,
                            software=SOFTWARE_VERSION) as infile:

                infile.save(to_save[:, :, i],
                            compress=6,
                            resolution=resolution,
                            metadata=metadata,
                            datetime=image.date,
                            extratags=page_tags)
Пример #15
0
def write(filename,
          image,
          sed=None,
          optical=None,
          ranges=None,
          multichannel=True,
          write_float=False):
    """Writes MIBI data to a multipage TIFF.

    Args:
        filename: The path to the target file if multi-channel, or the path to
            a folder if single-channel.
        image: A ``mibitof.mibi_image.MibiImage`` instance.
        sed: Optional, an array of the SED image data. This is assumed to be
            grayscale even if 3-dimensional, in which case only one channel
            will be used.
        optical: Optional, an RGB array of the optical image data.
        ranges: A list of (min, max) tuples the same length as the number of
            channels. If None, the min will default to zero and the max to the
            max pixel value in that channel. This is used by some external
            software to calibrate the display.
        multichannel: Boolean for whether to create a single multi-channel TIFF,
            or a folder of single-channel TIFFs. Defaults to True; if False,
            the sed and optical options are ignored.
        write_float: If True, saves the image data as float32 values (for
            opening properly in certain software such as Halo). Defaults to
            False which will save the image data as uint16. Note: setting
            write_float to True does not normalize or scale the data before
            saving, however saves the integer counts as floating point numbers.

    Raises:
        ValueError: Raised if the image is not a
            ``mibitof.mibi_image.MibiImage`` instance, or if its coordinates
            run date, or size are None.
    """
    if not isinstance(image, mi.MibiImage):
        raise ValueError('image must be a mibitof.mibi_image.MibiImage '
                         'instance.')
    if image.coordinates is None or image.size is None:
        raise ValueError('Image coordinates and size must not be None.')
    if image.masses is None or image.targets is None:
        raise ValueError(
            'Image channels must contain both masses and targets.')
    if np.issubdtype(image.data.dtype, np.integer) and not write_float:
        range_dtype = 'I'
    else:
        range_dtype = 'd'
    if ranges is None:
        ranges = [(0, m) for m in image.data.max(axis=(0, 1))]

    coordinates = [
        (286, '2i', 1, _motor_to_cm(image.coordinates[0])),  # x-position
        (287, '2i', 1, _motor_to_cm(image.coordinates[1])),  # y-position
    ]
    resolution = (image.data.shape[0] * 1e4 / float(image.size),
                  image.data.shape[1] * 1e4 / float(image.size), 'cm')

    metadata = {
        'mibi.run': getattr(image, 'run'),
        'mibi.version': getattr(image, 'version'),
        'mibi.instrument': getattr(image, 'instrument'),
        'mibi.slide': getattr(image, 'slide'),
        'mibi.dwell': getattr(image, 'dwell'),
        'mibi.scans': getattr(image, 'scans'),
        'mibi.aperture': getattr(image, 'aperture'),
        'mibi.description': getattr(image, 'point_name'),
        'mibi.folder': getattr(image, 'folder'),
        'mibi.tissue': getattr(image, 'tissue'),
        'mibi.panel': getattr(image, 'panel'),
        'mibi.mass_offset': getattr(image, 'mass_offset'),
        'mibi.mass_gain': getattr(image, 'mass_gain'),
        'mibi.time_resolution': getattr(image, 'time_resolution'),
        'mibi.miscalibrated': getattr(image, 'miscalibrated'),
        'mibi.check_reg': getattr(image, 'check_reg'),
        'mibi.filename': getattr(image, 'filename'),
    }
    description = {
        key: val
        for key, val in metadata.items() if val is not None
    }

    if multichannel:
        targets = list(image.targets)
        util.sort_channel_names(targets)
        indices = image.channel_inds(targets)
        with TiffWriter(filename, software=SOFTWARE_VERSION) as infile:
            for i in indices:
                metadata = description.copy()
                metadata.update({
                    'image.type': 'SIMS',
                    'channel.mass': int(image.masses[i]),
                    'channel.target': image.targets[i],
                })
                page_name = (285, 's', 0,
                             '{} ({})'.format(image.targets[i],
                                              image.masses[i]))
                min_value = (340, range_dtype, 1, ranges[i][0])
                max_value = (341, range_dtype, 1, ranges[i][1])
                page_tags = coordinates + [page_name, min_value, max_value]

                if write_float:
                    to_save = image.data[:, :, i].astype(np.float32)
                else:
                    to_save = image.data[:, :, i]

                infile.save(to_save,
                            compress=6,
                            resolution=resolution,
                            extratags=page_tags,
                            metadata=metadata,
                            datetime=image.date)
            if sed is not None:
                if sed.ndim > 2:
                    sed = sed[:, :, 0]

                sed_resolution = (sed.shape[0] * 1e4 / float(image.size),
                                  sed.shape[1] * 1e4 / float(image.size), 'cm')

                page_name = (285, 's', 0, 'SED')
                page_tags = coordinates + [page_name]
                infile.save(sed,
                            compress=6,
                            resolution=sed_resolution,
                            extratags=page_tags,
                            metadata={'image.type': 'SED'})
            if optical is not None:
                infile.save(optical,
                            compress=6,
                            metadata={'image.type': 'Optical'})
                label_coordinates = (_TOP_LABEL_COORDINATES
                                     if image.coordinates[1] > 0 else
                                     _BOTTOM_LABEL_COORDINATES)
                slide_label = np.fliplr(
                    np.moveaxis(
                        optical[
                            label_coordinates[0][0]:label_coordinates[0][1],
                            label_coordinates[1][0]:label_coordinates[1][1]],
                        0, 1))
                infile.save(slide_label,
                            compress=6,
                            metadata={'image.type': 'Label'})

    else:
        for i in range(image.data.shape[2]):
            metadata = description.copy()
            metadata.update({
                'image.type': 'SIMS',
                'channel.mass': int(image.masses[i]),
                'channel.target': image.targets[i],
            })
            page_name = (285, 's', 0, '{} ({})'.format(image.targets[i],
                                                       image.masses[i]))
            min_value = (340, range_dtype, 1, ranges[i][0])
            max_value = (341, range_dtype, 1, ranges[i][1])
            page_tags = coordinates + [page_name, min_value, max_value]

            if write_float:
                target_filename = os.path.join(
                    filename, '{}.float.tiff'.format(
                        util.format_for_filename(image.targets[i])))
            else:
                target_filename = os.path.join(
                    filename, '{}.tiff'.format(
                        util.format_for_filename(image.targets[i])))

            with TiffWriter(target_filename,
                            software=SOFTWARE_VERSION) as infile:

                if write_float:
                    to_save = image.data[:, :, i].astype(np.float32)
                else:
                    to_save = image.data[:, :, i]

                infile.save(to_save,
                            compress=6,
                            resolution=resolution,
                            metadata=metadata,
                            datetime=image.date,
                            extratags=page_tags)
Пример #16
0
    x_resolution = (2585297, 1000000)
    y_resolution = (2585297, 1000000)
    ######################################################################################
    resolution = (x_resolution, y_resolution, None)
    # the resolution argument has the syntax
    # resolution : (float, float[, str]) or ((int, int), (int, int)[, str])
    ######################################################################################

    with TiffFile(os.path.join(RAWDIR, filename)) as tif:

        data = tif.asarray()

        print data.shape

        nFrames = data.shape[0]

        print "nFrames =", nFrames

        for i in range(nFrames):

            outname = os.path.join(
                OUTDIR, framename + str(i + 1).zfill(ZERO_PADDING) + '.tif')

            image = data[i]

            print i, image.shape, "writing to ->", outname

            with TiffWriter(outname) as tifw:

                tifw.save(image, resolution=resolution)
Пример #17
0
def tiff(data, path):
    """Write out a TIFF stack"""
    with TiffWriter(path) as tif:
        for i in range(data.shape[0]):
            tif.save(data[i, :, :], compress=6)
Пример #18
0
        io = np.asarray(osh.read_region((x, y), 3, (tile_size+tile_pad,tile_size+tile_pad)))[:,:,0:3]

        arr_out = sklearn.feature_extraction.image.extract_patches(io,(patch_size,patch_size,3),stride_size)
        arr_out_shape = arr_out.shape
        arr_out = arr_out.reshape(-1,patch_size,patch_size,3)

        for batch_arr in divide_batch(arr_out,1):

            arr_out_gpu = torch.from_numpy(batch_arr.transpose(0, 3, 1, 2) / 255).type('torch.FloatTensor').to(device)
            #print("arr_out_gpu", arr_out_gpu)
            output_batch = model(arr_out_gpu)
            #make_dot(output_batch)
            output_batch = output_batch.detach().cpu().numpy()
            output_batch_color = cmap(output_batch.argmax(axis=1), alpha=None)[:,0:3]
            output = np.append(output,output_batch_color[:,:,None,None],axis=0)

        output = output.transpose((0, 2, 3, 1))
        output = output.reshape(arr_out_shape[0],arr_out_shape[1],patch_size//patch_size,patch_size//patch_size,output.shape[3])

        output=np.concatenate(np.concatenate(output,1),1)
        #print(y//stride_size//ds,y//stride_size//ds+tile_size//stride_size,x//stride_size//ds,x//stride_size//ds+tile_size//stride_size)
        npmm[y//stride_size//ds:y//stride_size//ds+tile_size//stride_size,x//stride_size//ds:x//stride_size//ds+tile_size//stride_size,:]=output*255

from skimage.external.tifffile import TiffWriter
with TiffWriter(f'/home/sudopizzai/Documents/data/images/TCGA-OL-A5RW-01Z-00-DX1.E16DE8EE-31AF-4EAF-A85F-DB3E3E2C3BFF_{patch_size}_{batch_size}_{level}_{mask_level}_{shape[0]}_{shape[1]}_{stride_size}_{tile_size}_{downsamples_level}_{cycle_step}_svs.tif', bigtiff=True, imagej=True) as tif:
    tif.save(npmm, compress=0, tile=(256,256))

image = Image.open(f'/home/sudopizzai/Documents/data/images/TCGA-OL-A5RW-01Z-00-DX1.E16DE8EE-31AF-4EAF-A85F-DB3E3E2C3BFF_{patch_size}_{batch_size}_{level}_{mask_level}_{shape[0]}_{shape[1]}_{stride_size}_{tile_size}_{downsamples_level}_{cycle_step}_svs.tif')
image.mode = 'I'
image.point(lambda i:i*(1./256)).convert('L').save(f'/home/sudopizzai/Documents/data/images/TCGA-OL-A5RW-01Z-00-DX1.E16DE8EE-31AF-4EAF-A85F-DB3E3E2C3BFF_{patch_size}_{batch_size}_{level}_{mask_level}_{shape[0]}_{shape[1]}_{stride_size}_{tile_size}_{downsamples_level}_{cycle_step}_svs.jpeg')
Пример #19
0
def saveStackAsTiff(graph_stack, outputTiff):
    data = asarray(graph_stack.getImageStack())
    with TiffWriter(outputTiff, bigtiff=True) as tiff:
        for i in range(data.shape[0]):
            tiff.save(data[i], photometric='rgb')