How to use tifffile - 10 common examples

To help you get started, we’ve selected a few tifffile examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PingjunChen / LiverCancerSeg / seg / pred_test_slide.py View on Github external
for ind, coor in enumerate(patch_coors):
                    ph, pw = coor[0], coor[1]
                    pred_map[ph:ph+args.patch_len, pw:pw+args.patch_len] += preds[ind]
                ttl_samples += inputs.size(0)

        prob_pred = np.divide(pred_map, wmap)
        slide_pred = (prob_pred > 0.5).astype(np.uint8)
        pred_save_path = os.path.join(result_dir, cur_slide + "_" + args.tumor_type + ".tif")
        io.imsave(pred_save_path, slide_pred*255)

        if args.save_org and args.tumor_type == "viable":
            org_w, org_h = wsi_head.level_dimensions[0]
            org_pred = transform.resize(prob_pred, (org_h, org_w))
            org_pred = (org_pred > 0.5).astype(np.uint8)
            org_save_path = os.path.join(org_result_dir, cur_slide[-3:] + ".tif")
            imsave(org_save_path, org_pred, compress=9)

    time_elapsed = time.time() - since
    print('Testing takes {:.0f}m {:.2f}s'.format(time_elapsed // 60, time_elapsed % 60))
github ilastik / ilastik / tests / test_lazyflow / test_operators / test_ioOperators / testOpTiffReader.py View on Github external
def test_unknown_axes_tags(self):
        """
        This test is related to https://github.com/ilastik/ilastik/issues/1487

        Here, we generate a 3D tiff file with scikit-learn and try to read it
        """
        import tifffile
        from distutils import version

        # TODO(Dominik) remove version checking once tifffile dependency is fixed
        # ilastik tiffile version >= 2000.0.0
        # latest tifffile version is 0.13.0 right now
        tifffile_version_ilastik_ref = version.StrictVersion("2000.0.0")
        tifffile_version_ref = version.StrictVersion("0.7.0")
        tifffile_version = version.StrictVersion(tifffile.__version__)

        testshapes = [((10, 20), "yx"), ((10, 20, 30), "zyx"), ((10, 20, 30, 3), "zyxc"), ((5, 10, 20, 30, 3), "tzyxc")]

        with tempdir() as d:
            for test_shape, test_axes in testshapes:
                data = numpy.random.randint(0, 256, test_shape).astype(numpy.uint8)
                tiff_path = "{}/myfile_{}.tiff".format(d, test_axes)
                # TODO(Dominik) remove version checking once dependencies for
                # skimage are >= 0.13.0 for all flavours of ilastik
                if (tifffile_version > tifffile_version_ilastik_ref) or (tifffile_version < tifffile_version_ref):
                    tifffile.imsave(tiff_path, data)
                else:
                    tifffile.imsave(tiff_path, data, metadata={"axes": "QQQ"})
                op = OpTiffReader(graph=Graph())
                op.Filepath.setValue(tiff_path)
                assert op.Output.ready()
github ilastik / lazyflow / tests / test_lazyflow / test_operators / test_ioOperators / testOpTiffReader.py View on Github external
def test_unknown_axes_tags(self):
        """
        This test is related to https://github.com/ilastik/ilastik/issues/1487

        Here, we generate a 3D tiff file with scikit-learn and try to read it
        """
        import tifffile
        from distutils import version

        # TODO(Dominik) remove version checking once tifffile dependency is fixed
        # ilastik tiffile version >= 2000.0.0
        # latest tifffile version is 0.13.0 right now
        tifffile_version_ilastik_ref = version.StrictVersion("2000.0.0")
        tifffile_version_ref = version.StrictVersion("0.7.0")
        tifffile_version = version.StrictVersion(tifffile.__version__)

        testshapes = [((10, 20), "yx"), ((10, 20, 30), "zyx"), ((10, 20, 30, 3), "zyxc"), ((5, 10, 20, 30, 3), "tzyxc")]

        with tempdir() as d:
            for test_shape, test_axes in testshapes:
                data = numpy.random.randint(0, 256, test_shape).astype(numpy.uint8)
                tiff_path = "{}/myfile_{}.tiff".format(d, test_axes)
                # TODO(Dominik) remove version checking once dependencies for
                # skimage are >= 0.13.0 for all flavours of ilastik
                if (tifffile_version > tifffile_version_ilastik_ref) or (tifffile_version < tifffile_version_ref):
                    tifffile.imsave(tiff_path, data)
                else:
                    tifffile.imsave(tiff_path, data, metadata={"axes": "QQQ"})
                op = OpTiffReader(graph=Graph())
                op.Filepath.setValue(tiff_path)
                assert op.Output.ready()
github tlambert03 / LLSpy / llspy / gui / img_dialog.py View on Github external
fft[c] = np.fft.ifft2(self.data[curT, c])
        fftWin = ImgDialog(fft, title=self.title + " FFT", shifted=True)
        fftWin.show()

    @QtCore.pyqtSlot()
    def fftShiftChecked(self, checked):
        self.data.setFFTshifted(checked)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    if len(sys.argv) > 1:
        import tifffile as tf

        path = sys.argv[1]
        im = tf.imread(path)
        if "fft" in sys.argv:
            im = np.fft.fftshift(np.fft.fftn(np.fft.fftshift(im)))
        path = os.path.basename(path)
    else:
        path = None
        im = np.random.rand(4, 2, 10, 100, 100) * 32000
    main = ImgDialog(im, title=path or "Figure")
    main.show()

    sys.exit(app.exec_())
github flika-org / flika / tifffile.py View on Github external
test_tifffile(path, settings.verbose)
        return 0

    if any(i in path for i in '?*'):
        path = glob.glob(path)
        if not path:
            print('no files match the pattern')
            return 0
        # TODO: handle image sequences
        #if len(path) == 1:
        path = path[0]

    print("Reading file structure...", end=' ')
    start = time.time()
    try:
        tif = TiffFile(path, multifile=not settings.nomultifile)
    except Exception as e:
        if settings.debug:
            raise
        else:
            print("\n", e)
            sys.exit(0)
    print("%.3f ms" % ((time.time()-start) * 1e3))

    if tif.is_ome:
        settings.norgb = True

    images = [(None, tif[0 if settings.page < 0 else settings.page])]
    if not settings.noplot:
        print("Reading image data... ", end=' ')
        notnone = lambda x: next(i for i in x if i is not None)
        start = time.time()
github fedebarabas / tormenta / tormenta / control / control.py View on Github external
def twoColorTIFF(self):

        cropName = utils.insertSuffix(self.savename, '_corrected')

        with tiff.TiffWriter(self.savename, software='Tormenta') as storeFile,\
                tiff.TiffWriter(cropName, software='Tormenta') as cropFile:

            while self.j < self.shape[0] and self.pressed:

                time.sleep(self.t_exp.magnitude)
                if self.andor.n_images_acquired > self.j:
                    i, self.j = self.andor.new_images_index
                    newImages = self.andor.images16(i, self.j, self.frameShape,
                                                    1, self.n)
                    self.sigUpdate.emit(np.transpose(newImages[-1]))
#                    self.sigUpdate.emit(newImages[-1])
                    newData = newImages[:, ::-1]

                    # This is done frame by frame in order to have contiguously
                    # saved tiff files so they're correctly opened in ImageJ
                    # or in python through tifffile
github flika-org / flika / tifffile.py View on Github external
continue
                elif isinstance(v[0], TiffPage):
                    v = [i.index for i in v if i]
            s.append(
                ("* %s: %s" % (k, str(v))).split("\n", 1)[0]
                [:PRINT_LINE_LEN].rstrip())
        for k, v in lists:
            l = []
            for i, w in enumerate(v):
                l.append("* %s[%i]\n  %s" % (k, i,
                                             str(w).replace("\n", "\n  ")))
            s.append('\n'.join(l))
        return '\n'.join(s)


class TiffTags(Record):
    """Dictionary of TiffTags with attribute access."""
    def __str__(self):
        """Return string with information about all tags."""
        s = []
        #sortbycode = lambda a, b: cmp(a.code, b.code)
        #for tag in sorted(self.values(), sortbycode):
        for tag in sorted(self.values(), key=lambda x: x.code):
            typecode = "%i%s" % (tag.count * int(tag.dtype[0]), tag.dtype[1])
            line = "* %i %s (%s) %s" % (tag.code, tag.name, typecode,
                                        str(tag.value).split('\n', 1)[0])
            s.append(line[:PRINT_LINE_LEN].lstrip())
        return '\n'.join(s)


def read_bytes(fh, byteorder, dtype, count):
    """Read tag data from file and return as byte string."""
github flika-org / flika / tifffile.py View on Github external
def __str__(self):
        """Pretty print Record."""
        s = []
        lists = []
        for k in sorted(self):
            if k.startswith('_'):  # does not work with byte
                continue
            v = self[k]
            if isinstance(v, (list, tuple)) and len(v):
                if isinstance(v[0], Record):
                    lists.append((k, v))
                    continue
                elif isinstance(v[0], TiffPage):
                    v = [i.index for i in v if i]
            s.append(
                ("* %s: %s" % (k, str(v))).split("\n", 1)[0]
                [:PRINT_LINE_LEN].rstrip())
        for k, v in lists:
            l = []
            for i, w in enumerate(v):
                l.append("* %s[%i]\n  %s" % (k, i,
                                             str(w).replace("\n", "\n  ")))
            s.append('\n'.join(l))
        return '\n'.join(s)
github tlambert03 / LLSpy / llspy / libcudawrapper.py View on Github external
angle = float(sys.argv[2]) if len(sys.argv) > 2 else 32.5
            dz = float(sys.argv[3]) if len(sys.argv) > 3 else 0.4
            dx = 0.1
            xzRatio = dx / (np.deg2rad(angle) * dz)
            rotated = rotateGPU(im, angle, xzRatio)
            tf.imshow(rotated, vmin=0, vmax=rotated.max() * 0.5)
            plt.show()

        elif (sys.argv[1] == "decon") or (sys.argv[1] == "deconv"):
            im = tf.imread(
                "/Users/talley/Dropbox (HMS)/CBMF/lattice_sample_data/lls_bidirectional/bidir_ch0_stack0000_488nm_0000000msec_0007232334msecAbs.tif"
            )
            otfpath = "/Users/talley/Dropbox (HMS)/CBMF/lattice_sample_data/lls_PSFs/488_otf.tif"
            RL_init(im.shape, otfpath, dzdata=0.4)
            decon = RL_decon(im, nIters=15)
            tf.imshow(decon, vmin=0, vmax=decon.max() * 0.5)
            plt.show()
            RL_cleanup()
        elif sys.argv[1] == "camcor":

            from llspy import llsdir
            from llspy import samples
            import time

            E = llsdir.LLSdir(samples.stickypix)

            # from llspy.util import util
            # from llspy.camera.camera import CameraParameters, CameraROI

            # camparams = CameraParameters()
            # camparams = camparams.get_subroi(CameraROI(E.settings.camera.roi))
github tlambert03 / LLSpy / llspy / libcudawrapper.py View on Github external
# for i in sys.argv[2:]:
            #   p = p = os.path.abspath(i).replace('\\', '')
            #   if os.path.isfile(p):
            #       tf.imshow(deskewGPU(tf.imread(p), float(zstep)))
            #       plt.show()

        elif sys.argv[1] == "rotate":
            im = tf.imread(
                "/Users/talley/Dropbox (HMS)/CBMF/lattice_sample_data/lls_registration_samp/reg_ex1/tspeck/GPUdecon/tspeck_ch0_stack0000_488nm_0000000msec_0001881189msecAbs_decon.tif"
            )
            angle = float(sys.argv[2]) if len(sys.argv) > 2 else 32.5
            dz = float(sys.argv[3]) if len(sys.argv) > 3 else 0.4
            dx = 0.1
            xzRatio = dx / (np.deg2rad(angle) * dz)
            rotated = rotateGPU(im, angle, xzRatio)
            tf.imshow(rotated, vmin=0, vmax=rotated.max() * 0.5)
            plt.show()

        elif (sys.argv[1] == "decon") or (sys.argv[1] == "deconv"):
            im = tf.imread(
                "/Users/talley/Dropbox (HMS)/CBMF/lattice_sample_data/lls_bidirectional/bidir_ch0_stack0000_488nm_0000000msec_0007232334msecAbs.tif"
            )
            otfpath = "/Users/talley/Dropbox (HMS)/CBMF/lattice_sample_data/lls_PSFs/488_otf.tif"
            RL_init(im.shape, otfpath, dzdata=0.4)
            decon = RL_decon(im, nIters=15)
            tf.imshow(decon, vmin=0, vmax=decon.max() * 0.5)
            plt.show()
            RL_cleanup()
        elif sys.argv[1] == "camcor":

            from llspy import llsdir
            from llspy import samples