Python tifffile.imsave() Examples

The following are 13 code examples of tifffile.imsave(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tifffile , or try the search function .
Example #1
Source File: io.py    From napari with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def imsave(filename: str, data: np.ndarray):
    """Custom implementation of imsave to avoid skimage dependency.

    Parameters
    ----------
    filename : string
        The path to write the file to.
    data : np.ndarray
        The image data.
    """
    ext = os.path.splitext(filename)[1]
    if ext in [".tif", ".tiff"]:
        import tifffile

        tifffile.imsave(filename, data)
    else:
        import imageio

        imageio.imsave(filename, data) 
Example #2
Source File: imgutils.py    From spimagine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write3dTiff(data,fName):
    imsave(fName,data)

        
# def getTiffSize(fName):
#     from PIL import Image
#     img = Image.open(fName, 'r')
#     depth = 0
#     while True:
#         try:
#             img.seek(depth)
#         except Exception as e:
#             break
#         depth += 1
#
#     return (depth,)+img.size[::-1] 
Example #3
Source File: TIF.py    From ClearMap with GNU General Public License v3.0 5 votes vote down vote up
def writeData(filename, data):
    """Write image data to tif file
    
    Arguments:
        filename (str): file name 
        data (array): image data
    
    Returns:
        str: tif file name
    """
    
    d = len(data.shape);
    
    if d == 2:
        #tiff.imsave(filename, data);
        tiff.imsave(filename, data.transpose([1,0]));
    elif d == 3:   
        #tiff.imsave(filename, data.transpose([2,0,1]));
        tiff.imsave(filename, data.transpose([2,1,0]));
    elif d == 4:        
        #tiffile (z,y,x,c)
        #t = tiff.TiffWriter(filename, bigtiff = True);
        #t.save(data.transpose([2,0,1,3]), photometric = 'minisblack',  planarconfig = 'contig');
        #t.save(data.transpose([2,1,0,3]), photometric = 'minisblack',  planarconfig = 'contig')
        #t.close();    
        tiff.imsave(filename, data.transpose([2,1,0,3]), photometric = 'minisblack',  planarconfig = 'contig', bigtiff = True);
    else:
        raise RuntimeError('writing multiple channel data to tif not supported!');
    
    return filename; 
Example #4
Source File: io_utils.py    From sentinelhub-py with MIT License 5 votes vote down vote up
def write_tiff_image(filename, image, compress=False):
    """ Write image data to TIFF file

    :param filename: name of file to write data to
    :type filename: str
    :param image: image data to write to file
    :type image: numpy array
    :param compress: whether to compress data. If `True`, lzma compression is used. Default is `False`
    :type compress: bool
    """
    if compress:
        return tiff.imsave(filename, image, compress='lzma')  # loseless compression, works very well on masks
    return tiff.imsave(filename, image) 
Example #5
Source File: run_tifffile.py    From recipy with Apache License 2.0 5 votes vote down vote up
def imsave(self):
        """
        Use tifffile.imsave to write image2.tiff.
        """
        file_name = os.path.join(self.data_dir, "image2.tiff")

        data = numpy.array([[1, 2, 3],
                            [4, 5, 6]])

        tifffile.imsave(file_name, data)
        os.remove(file_name) 
Example #6
Source File: create_patches_all.py    From SpaceNet_Off_Nadir_Solutions with Apache License 2.0 5 votes vote down vote up
def patches_and_cocoann(gt, outdir_rgb, outdir_mpan, count=1,create_anns=True):
    gt.index = gt.ImageId
    gt_flt = gt[gt.PolygonWKT_Geo != 'POLYGON EMPTY']
    gv = gt_flt.ImageId.value_counts()
    annotations = []
    images = []
    counter = count
    for u in gt_flt.ImageId.unique():
        try:
            pan_sharpen_dir = ''.join([RAW_DIR, gt.name, '/Pan-Sharpen/'])
            image_file = ''.join([pan_sharpen_dir, 'Pan-Sharpen', '_', u, '.tif'])
            img_rgb = tifffile.imread(image_file)
            if np.argmin(img_rgb.shape) == 0:
                img_rgb = np.transpose(img_rgb, (1, 2, 0))
            img_rgb = img_rgb[:, :, [3, 2, 1, 0]]
            img_mpan = get_pan_sharpend(''.join([RAW_DIR, gt.name, '/']), u)

        except:
            print('load error..', u)
            continue
        if gv[u] > 1:
            poly = gt.loc[u].PolygonWKT_Pix.apply(lambda x: loads(x)).values.tolist()
        else:
            poly = [loads(gt.loc[u].PolygonWKT_Pix)]
        mask = util.mask_for_polygons(poly, im_size=imsize)
        img_patches_rgb, mask_patches, kp = patch_creator.create(img=img_rgb, mask=mask, nonzero=True)
        img_patches_mpan, _, _ = patch_creator.create(img=img_mpan, mask=mask, nonzero=True)

        for i, k in enumerate(kp.keys()):
            file_name_rgb = os.path.join(outdir_rgb, ''.join([u, '_', str(k), '.tif']))
            file_name_mpan = os.path.join(outdir_mpan, ''.join([u, '_', str(k), '.tif']))
            if create_anns:
                anns, images_d, counter = create_coco_anns(file_name_rgb, counter, mask_patches[i].squeeze())
                annotations.extend(anns)
                images.extend(images_d)
            tifffile.imsave(file_name_mpan, img_patches_mpan[i].astype('uint16'))
            tifffile.imsave(file_name_rgb, img_patches_rgb[i].astype('uint16'))
        if DEBUG:
            break
    return annotations, images, counter 
Example #7
Source File: test-mvs.py    From dfc2019 with MIT License 5 votes vote down vote up
def merge_dsm_tifs(folder, count, outname):
    # loop on all input DSM images
    dsm_images = []
    cls_images = []
    for i in range(count):
        name = folder + '{:03d}'.format(i) + '_dsm.tif'
        if os.path.isfile(name):
            next_image = tifffile.imread(name)
            dsm_images.append(next_image)
        name = folder + '{:03d}'.format(i) + '_cls.tif'
        if os.path.isfile(name):
            next_image = tifffile.imread(name)
            cls_images.append(next_image)

    # compute median value for each pixel
    print('Length = ', len(dsm_images))
    dsm_images = np.array(dsm_images)
    cls_images = np.array(cls_images)
    print(dsm_images.shape)
    count = dsm_images.shape[0]
    ydim = dsm_images.shape[1]
    xdim = dsm_images.shape[2]
    median_dsm = np.zeros((ydim, xdim), dtype=np.float32)
    median_cls = np.zeros((ydim, xdim), dtype=np.uint8)
    for i in range(ydim):
        for j in range(xdim):
            pixel = dsm_images[:, i, j]
            pixel = pixel[pixel != NO_DATA]
            count = pixel.shape[0]
            if (count > 0):
                median_dsm[i, j] = np.median(pixel)
            else:
                median_dsm[i, j] = NO_DATA
            pixel = cls_images[:, i, j]
            median_cls[i, j] = get_most_frequent_category(pixel)

    # fill any remaining voids with the max value
    median_dsm[median_dsm == NO_DATA] = median_dsm.max()  # set to max height

    # convert CLS image to LAS conventions
    median_cls = sequential_to_las_labels(median_cls)

    # write median images
    tifffile.imsave(outname + '_DSM.tif', median_dsm)
    tifffile.imsave(outname + '_CLS.tif', median_cls)

    # write median images as uint8 tif for visualization
    median_u8_image = median_dsm - np.min(median_dsm)
    median_u8_image = np.uint8(np.round((median_u8_image / np.max(median_u8_image)) * 255))
    tifffile.imsave(outname + '_stereo_rgb.tif', median_u8_image)
    median_cls_rgb = las_to_sequential_labels(median_cls)
    median_cls_rgb = category_to_color(median_cls_rgb)
    tifffile.imsave(outname + '_segmentation_rgb.tif', median_cls_rgb)

    return median_dsm, median_cls


# main program to demonstrate a baseline MVS algorithm 
Example #8
Source File: train.py    From dfc2019 with MIT License 5 votes vote down vote up
def save_rgb_image(self, image, filepath):
#        size = [image.shape[0], image.shape[1]]
        minval = np.amin(image)
        maxval = np.amax(image)
        image = (image - minval)/ (maxval - minval + 0.01)
        image *= 255
        image = image.astype(np.uint8)
#        image = np.reshape(image, size)
        tifffile.imsave(filepath, image) 
Example #9
Source File: train.py    From dfc2019 with MIT License 5 votes vote down vote up
def save_disparity_image(self, image, filepath):
        size = [image.shape[0], image.shape[1]]
        minval = -self.dmax
        maxval = self.dmax
        image = (image - minval)/ (maxval - minval + 0.01)
        image[image < 0.0] = 0.0
        image[image > 1.0] = 1.0
        image *= 255
        image = image.astype(np.uint8)
        image = np.reshape(image, size)
        tifffile.imsave(filepath, image) 
Example #10
Source File: test.py    From vnlnet with GNU General Public License v3.0 5 votes vote down vote up
def write_file(f, img):
    """
    Write a file f.
    """
    img = np.squeeze(img)
    if f[-4:] == 'tiff' or f[-3:] == 'tif':
        tifffile.imsave(f, img)
    else:
        img = np.floor(img + 0.5)
        img[img < 0] = 0
        img[img > 255] = 255
        img = np.asarray(img, dtype=np.uint8)
        imageio.imwrite(f, img) 
Example #11
Source File: dftreg.py    From sima with GNU General Public License v2.0 5 votes vote down vote up
def _save_registered_frames(frames, save_name, save_fmt, verbose=False):
    """
    Save. Only use for debugging.
    Parameters
    ----------
    Returns
    -------
    """
    if verbose:
        print('    Saving...')
    try:  # this is ugly
        import tifffile
    except ImportError:
        try:
            from sima.misc import tifffile
        except ImportError:
            if verbose:
                print('        Cannot find tifffile')

    if save_fmt == 'singles':
        for idx in range(frames.shape[0]):
            tifffile.imsave(
                save_name + '_' + '{number:05d}'.format(number=idx) +
                '_DFTreg.tif', frames[idx].astype(np.uint16))
    if save_fmt == 'mptiff':
        tifffile.imsave(save_name + '_DFTreg.tif',
                        frames.astype(np.uint16))
    elif save_fmt == 'bigtiff':
        tifffile.imsave(save_name + '_DFTreg.tif',
                        frames.astype(np.uint16), bigtiff=True) 
Example #12
Source File: metric_gen.py    From PSSR with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def stack_process(pred, bilinear, gt, offset_frames=0):
    stack_pred = PIL.Image.open(pred)
    stack_bilinear = PIL.Image.open(bilinear)
    stack_gt  = PIL.Image.open(gt)

    stem_pred = Path(pred).stem
    stem_bilinear = Path(bilinear).stem
    stem_gt = Path(gt).stem

    frames = stack_pred.n_frames
    stack_psnr = []
    stack_lpsnr = []
    stack_ssim = []
    stack_lssim = []
    pred_slice_name = []
    bilinear_slice_name = []
    gt_slice_name = []
    #y_norm1s = []
    #x1_norms = []
    #y_norm2s = []
    #x2_norms = []

    for i in range(frames):
        stack_pred.seek(i)
        stack_bilinear.seek(i) if frames == 1 else stack_bilinear.seek(i+offset_frames)
        stack_gt.seek(i) if frames == 1 else stack_gt.seek(i+offset_frames)

        x1 = np.array(stack_pred).astype(np.float32)
        x2 = np.array(stack_bilinear).astype(np.float32)
        y = np.array(stack_gt).astype(np.float32)
        psnr, ssim, l_psnr, l_ssim, y_norm1, x1_norm, y_norm2, x2_norm = slice_process(x1, x2, y)

        stack_psnr.append(psnr)
        stack_lpsnr.append(l_psnr)
        stack_ssim.append(ssim)
        stack_lssim.append(l_ssim)

        pred_slice_name.append(f'{stem_pred}_z{i}.tif')
        bilinear_slice_name.append(f'{stem_bilinear}_z{i+offset_frames}.tif')
        gt_slice_name.append(f'{stem_gt}_z{i+offset_frames}.tif')
        #y_norm1s.append(np.array(y_norm1).copy())
        #x1_norms.append(np.array(x1_norm).copy())
        #y_norm2s.append(np.array(y_norm2).copy())
        #x2_norms.append(np.array(x2_norm).copy())


    #tifffile.imsave(str(exp_dir/f"{stem}_GTnormtopred.tif"), np.stack(y_norm1s).astype(np.float32))
    #tifffile.imsave(str(exp_dir/f"{stem}_prednorm.tif"), np.stack(x1_norms).astype(np.float32))
    #tifffile.imsave(str(exp_dir/f"{stem}_GTnormtobilinear.tif"), np.stack(y_norm2s).astype(np.float32))
    #tifffile.imsave(str(exp_dir/f"{stem}_bilinearnorm.tif"), np.stack(x2_norms).astype(np.float32))
    return pred_slice_name,bilinear_slice_name,gt_slice_name,stack_psnr,stack_ssim,stack_lpsnr,stack_lssim 
Example #13
Source File: io.py    From napari with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def imsave_extensions() -> Tuple[str, ...]:
    """Valid extensions of files that imsave can write to.

    Returns
    ----------
    tuple
        Valid extensions of files that imsave can write to.
    """
    # import imageio
    # return tuple(set(x for f in imageio.formats for x in f.extensions))

    # The above method generates a lot of extensions that will fail.  This list
    # is a more realistic set, generated by trying to write a variety of numpy
    # arrays (skimage.data.camera, grass, and some random numpy arrays/shapes).
    # TODO: maybe write a proper imageio plugin.
    return (
        '.bmp',
        '.bsdf',
        '.bw',
        '.eps',
        '.gif',
        '.icns',
        '.ico',
        '.im',
        '.j2c',
        '.j2k',
        '.jfif',
        '.jp2',
        '.jpc',
        '.jpe',
        '.jpeg',
        '.jpf',
        '.jpg',
        '.jpx',
        '.lsm',
        '.mpo',
        '.npz',
        '.pbm',
        '.pcx',
        '.pgm',
        '.png',
        '.ppm',
        '.ps',
        '.rgb',
        '.rgba',
        '.sgi',
        '.stk',
        '.tga',
        '.tif',
        '.tiff',
    )