How to use the tifffile.Record function in tifffile

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 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 flika-org / flika / tifffile.py View on Github external
self.dtype = self.tags['color_map'].dtype[1]
            self.color_map = numpy.array(self.color_map, self.dtype)
            dmax = self.color_map.max()
            if dmax < 256:
                self.dtype = numpy.uint8
                self.color_map = self.color_map.astype(self.dtype)
            #else:
            #    self.dtype = numpy.uint8
            #    self.color_map >>= 8
            #    self.color_map = self.color_map.astype(self.dtype)
            self.color_map.shape = (3, -1)

        if self.is_stk:
            # consolidate mm_uci tags
            planes = tags['mm_uic2'].count
            self.mm_uic_tags = Record(tags['mm_uic2'].value)
            for key in ('mm_uic3', 'mm_uic4', 'mm_uic1'):
                if key in tags:
                    self.mm_uic_tags.update(tags[key].value)
            if self.planar_configuration == 'contig':
                self._shape = (planes, 1, self.image_length, self.image_width,
                               self.samples_per_pixel)
                self.shape = tuple(self._shape[i] for i in (0, 2, 3, 4))
                self.axes = 'PYXS'
            else:
                self._shape = (planes, self.samples_per_pixel,
                               self.image_length, self.image_width, 1)
                self.shape = self._shape[:4]
                self.axes = 'PSYX'
            if self.is_palette and (self.color_map.shape[1]
                                    >= 2**self.bits_per_sample):
                self.shape = (3, planes, self.image_length, self.image_width)
github flika-org / flika / tifffile.py View on Github external
self._tiffs[uuid.text] = tf
                            pages = self._tiffs[uuid.text].pages
                            try:
                                for i in range(num if num else len(pages)):
                                    ifds[idx + i] = pages[ifd + i]
                            except IndexError:
                                warnings.warn("ome-xml: index out of range")
                            break
                    else:
                        pages = self.pages
                        try:
                            for i in range(num if num else len(pages)):
                                ifds[idx + i] = pages[ifd + i]
                        except IndexError:
                            warnings.warn("ome-xml: index out of range")
                result.append(Record(axes=axes, shape=shape, pages=ifds,
                                     dtype=numpy.dtype(ifds[0].dtype)))

        for record in result:
            for axis, (newaxis, labels) in modulo.items():
                i = record.axes.index(axis)
                size = len(labels)
                if record.shape[i] == size:
                    record.axes = record.axes.replace(axis, newaxis, 1)
                else:
                    record.shape[i] //= size
                    record.shape.insert(i+1, size)
                    record.axes = record.axes.replace(axis, axis+newaxis, 1)

        return result
github flika-org / flika / tifffile.py View on Github external
value = stripnull(fh.read(size))
        elif dtype == 4:
            value = unpack(byteorder+"i", fh.read(4))[0]
        elif dtype == 5:
            value = unpack(byteorder+"d", fh.read(8))[0]
        else:
            value = 0
        if entry in CZ_LSM_SCAN_INFO_ARRAYS:
            blocks.append(block)
            name = CZ_LSM_SCAN_INFO_ARRAYS[entry]
            newobj = []
            setattr(block, name, newobj)
            block = newobj
        elif entry in CZ_LSM_SCAN_INFO_STRUCTS:
            blocks.append(block)
            newobj = Record()
            block.append(newobj)
            block = newobj
        elif entry in CZ_LSM_SCAN_INFO_ATTRIBUTES:
            name = CZ_LSM_SCAN_INFO_ATTRIBUTES[entry]
            setattr(block, name, value)
        elif entry == 0xffffffff:
            block = blocks.pop()
        else:
            setattr(block, "unknown_%x" % entry, value)
        if not blocks:
            break
    return block
github flika-org / flika / tifffile.py View on Github external
dtype=numpy.dtype(self.pages[0].dtype))]

        if not series:
            shapes = []
            pages = {}
            for page in self.pages:
                if not page.shape:
                    continue
                shape = page.shape + (page.axes,
                                      page.compression in TIFF_DECOMPESSORS)
                if not shape in pages:
                    shapes.append(shape)
                    pages[shape] = [page]
                else:
                    pages[shape].append(page)
            series = [Record(pages=pages[s],
                             axes=(('I' + s[-2])
                                   if len(pages[s]) > 1 else s[-2]),
                             dtype=numpy.dtype(pages[s][0].dtype),
                             shape=((len(pages[s]), ) + s[:-2]
                                    if len(pages[s]) > 1 else s[:-2]))
                      for s in shapes]
        return series
github flika-org / flika / tifffile.py View on Github external
size = struct.calcsize(fmt)
        if size > parent.offset_size or code in CUSTOM_TAGS:
            pos = fh.tell()
            tof = {4: 'I', 8: 'Q'}[parent.offset_size]
            self.value_offset = offset = struct.unpack(byteorder+tof, value)[0]
            if offset < 0 or offset > parent._fsize:
                raise TiffTag.Error("corrupt file - invalid tag value offset")
            elif offset < 4:
                raise TiffTag.Error("corrupt value offset for tag %i" % code)
            fh.seek(offset)
            if code in CUSTOM_TAGS:
                readfunc = CUSTOM_TAGS[code][1]
                value = readfunc(fh, byteorder, dtype, count)
                fh.seek(0, 2)  # bug in numpy/Python 3.x ?
                if isinstance(value, dict):  # numpy.core.records.record
                    value = Record(value)
            elif code in TIFF_TAGS or dtype[-1] == 's':
                value = struct.unpack(fmt, fh.read(size))
            else:
                value = read_numpy(fh, byteorder, dtype, count)
                fh.seek(0, 2)  # bug in numpy/Python 3.x ?
            fh.seek(pos)
        else:
            value = struct.unpack(fmt, value[:size])

        if not code in CUSTOM_TAGS:
            if len(value) == 1:
                value = value[0]

        if dtype.endswith('s'):
            value = stripnull(value)
github flika-org / flika / tifffile.py View on Github external
print("\nTIFF file:", tif)
    print()
    for i, s in enumerate(tif.series):
        print ("Series %i" % i)
        print(s)
        print()
    for i, page in images:
        print(page)
        print(page.tags)
        if page.is_palette:
            print("\nColor Map:", page.color_map.shape, page.color_map.dtype)
        for attr in ('cz_lsm_info', 'cz_lsm_scan_information', 'mm_uic_tags',
                     'mm_header', 'imagej_tags', 'nih_image_header'):
            if hasattr(page, attr):
                print("", attr.upper(), Record(getattr(page, attr)), sep="\n")
        print()

    if images and not settings.noplot:
        try:
            import matplotlib
            matplotlib.use('TkAgg')
            from matplotlib import pyplot
        except ImportError as e:
            warnings.warn("failed to import matplotlib.\n%s" % e)
        else:
            for img, page in images:
                if img is None:
                    continue
                vmin, vmax = None, None
                if 'gdal_nodata' in page.tags:
                    vmin = numpy.min(img[img > float(page.gdal_nodata)])
github flika-org / flika / tifffile.py View on Github external
self.strips_per_image = 0

        key = (self.sample_format, self.bits_per_sample)
        self.dtype = self._dtype = TIFF_SAMPLE_DTYPES.get(key, None)

        if self.is_imagej:
            # consolidate imagej meta data
            adict = imagej_description(tags['image_description'].value)
            try:
                adict.update(imagej_meta_data(
                    tags['imagej_meta_data'].value,
                    tags['imagej_byte_counts'].value,
                    self.parent.byteorder))
            except Exception:
                pass
            self.imagej_tags = Record(adict)

        if not 'image_length' in self.tags or not 'image_width' in self.tags:
            # some GEL file pages are missing image data
            self.image_length = 0
            self.image_width = 0
            self.strip_offsets = 0
            self._shape = ()
            self.shape = ()
            self.axes = ''

        if self.is_palette:
            self.dtype = self.tags['color_map'].dtype[1]
            self.color_map = numpy.array(self.color_map, self.dtype)
            dmax = self.color_map.max()
            if dmax < 256:
                self.dtype = numpy.uint8