code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if out is not None and not out.flags.writeable:
out = None
if isinstance(data, (bytes, bytearray)):
data = numpy.frombuffer(data, dtype='u1')
return numpy.cumsum(data, axis=0, dtype='u1', out=out).tobytes()
if data.dtype.kind == 'f':
view = data.view('u%i' % data.dtype.i... | def delta_decode(data, axis=-1, out=None) | Decode Delta. | 2.480856 | 2.483747 | 0.998836 |
if not _bitorder:
_bitorder.append(
b'\x00\x80@\xc0 \xa0`\xe0\x10\x90P\xd00\xb0p\xf0\x08\x88H\xc8('
b'\xa8h\xe8\x18\x98X\xd88\xb8x\xf8\x04\x84D\xc4$\xa4d\xe4\x14'
b'\x94T\xd44\xb4t\xf4\x0c\x8cL\xcc,\xacl\xec\x1c\x9c\\\xdc<\xbc|'
b'\xfc\x02\x82B\xc2"\xa2b\... | def bitorder_decode(data, out=None, _bitorder=[]) | Reverse bits in each byte of byte string or numpy array.
Decode data where pixels with lower column values are stored in the
lower-order bits of the bytes (TIFF FillOrder is LSB2MSB).
Parameters
----------
data : byte string or ndarray
The data to be bit reversed. If byte string, a new bit... | 2.36757 | 2.418637 | 0.978886 |
if numbits == 1: # bitarray
data = numpy.frombuffer(data, '|B')
data = numpy.unpackbits(data)
if runlen % 8:
data = data.reshape(-1, runlen + (8 - runlen % 8))
data = data[:, :runlen].reshape(-1)
return data.astype(dtype)
if numbits in (8, 16, 32, 64... | def packints_decode(data, dtype, numbits, runlen=0, out=None) | Decompress byte string to array of integers.
This implementation only handles itemsizes 1, 8, 16, 32, and 64 bits.
Install the imagecodecs package for decoding other integer sizes.
Parameters
----------
data : byte str
Data to decompress.
dtype : numpy.dtype or str
A numpy bool... | 2.60766 | 2.959293 | 0.881177 |
image = numpy.take(colormap, image, axis=1)
image = numpy.rollaxis(image, 0, image.ndim)
if contig:
image = numpy.ascontiguousarray(image)
return image | def apply_colormap(image, colormap, contig=True) | Return palette-colored image.
The image values are used to index the colormap on axis 1. The returned
image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype.
Parameters
----------
image : numpy.ndarray
Indexes into the colormap.
colormap : numpy.ndarray
RGB lo... | 2.573184 | 3.089473 | 0.832888 |
orient = TIFF.ORIENTATION
orientation = enumarg(orient, orientation)
if orientation == orient.TOPLEFT:
return image
if orientation == orient.TOPRIGHT:
return image[..., ::-1, :]
if orientation == orient.BOTLEFT:
return image[..., ::-1, :, :]
if orientation == orient... | def reorient(image, orientation) | Return reoriented view of image array.
Parameters
----------
image : numpy.ndarray
Non-squeezed output of asarray() functions.
Axes -3 and -2 must be image length and width respectively.
orientation : int or str
One of TIFF.ORIENTATION names or values. | 1.790141 | 1.850856 | 0.967196 |
a = numpy.asarray(a)
reshape = []
shape = []
strides = []
for i, j, k in zip(a.strides, a.shape, repeats):
shape.extend((j, k))
strides.extend((i, 0))
reshape.append(j * k)
return numpy.lib.stride_tricks.as_strided(
a, shape, strides, writeable=False).reshape... | def repeat_nd(a, repeats) | Return read-only view into input array with elements repeated.
Zoom nD image by integer factors using nearest neighbor interpolation
(box filter).
Parameters
----------
a : array_like
Input array.
repeats : sequence of int
The number of repetitions to apply along each dimension... | 2.775691 | 3.130112 | 0.886771 |
is_shape = isinstance(data_or_shape, tuple)
shape = data_or_shape if is_shape else data_or_shape.shape
if len(shape) >= ndim:
return data_or_shape
shape = (1,) * (ndim - len(shape)) + shape
return shape if is_shape else data_or_shape.reshape(shape) | def reshape_nd(data_or_shape, ndim) | Return image array or shape with at least ndim dimensions.
Prepend 1s to image shape as necessary.
>>> reshape_nd(numpy.empty(0), 1).shape
(0,)
>>> reshape_nd(numpy.empty(1), 2).shape
(1, 1)
>>> reshape_nd(numpy.empty((2, 3)), 3).shape
(1, 2, 3)
>>> reshape_nd(numpy.empty((3, 4, 5)), 3... | 1.892003 | 2.262572 | 0.836218 |
if len(shape) != len(axes):
raise ValueError('dimensions of axes and shape do not match')
if skip is None:
skip = 'XY'
shape, axes = zip(*(i for i in zip(shape, axes)
if i[0] > 1 or i[1] in skip))
return tuple(shape), ''.join(axes) | def squeeze_axes(shape, axes, skip=None) | Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX') | 3.358411 | 3.453864 | 0.972363 |
for ax in axes:
if ax not in asaxes:
raise ValueError('unknown axis %s' % ax)
# add missing axes to image
if asaxes is None:
asaxes = 'CTZYX'
shape = image.shape
for ax in reversed(asaxes):
if ax not in axes:
axes = ax + axes
shape = (... | def transpose_axes(image, axes, asaxes=None) | Return image with its axes permuted to match specified axes.
A view is returned if possible.
>>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape
(5, 2, 1, 3, 4) | 2.748232 | 2.743985 | 1.001548 |
shape = tuple(shape)
newshape = tuple(newshape)
if len(axes) != len(shape):
raise ValueError('axes do not match shape')
size = product(shape)
newsize = product(newshape)
if size != newsize:
raise ValueError('cannot reshape %s to %s' % (shape, newshape))
if not axes or n... | def reshape_axes(axes, shape, newshape, unknown=None) | Return axes matching new shape.
By default, unknown dimensions are labelled 'Q'.
>>> reshape_axes('YXS', (219, 301, 1), (219, 301))
'YX'
>>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1))
'QQYQXQ' | 2.971514 | 3.071418 | 0.967473 |
npages = len(pages)
if npages == 0:
raise ValueError('no pages')
if npages == 1:
kwargs['maxworkers'] = maxworkers
return pages[0].asarray(out=out, **kwargs)
page0 = next(p for p in pages if p is not None).keyframe
page0.asarray(validate=None) # ThreadPoolExecutor swa... | def stack_pages(pages, out=None, maxworkers=None, **kwargs) | Read data from sequence of TiffPage and stack them vertically.
Additional parameters are passsed to the TiffPage.asarray function. | 3.610492 | 3.53699 | 1.020781 |
# TODO: cythonize this
offsets = list(offsets)
counts = list(counts)
size = len(offsets)
if size != len(counts):
raise ValueError('StripOffsets and StripByteCounts mismatch')
j = 0
for i, (o, b) in enumerate(zip(offsets, counts)):
if b > 0:
if o > 0:
... | def clean_offsetscounts(offsets, counts) | Return cleaned offsets and byte counts.
Remove zero offsets and counts.
Use to sanitize StripOffsets and StripByteCounts tag values. | 3.268145 | 2.955664 | 1.105723 |
if buffersize is None:
buffersize = 2**26
length = len(offsets)
i = 0
while i < length:
data = []
with lock:
size = 0
while size < buffersize and i < length:
fh.seek(offsets[i])
bytecount = bytecounts[i]
... | def buffered_read(fh, lock, offsets, bytecounts, buffersize=None) | Return iterator over segments read from file. | 2.389063 | 2.265738 | 1.05443 |
if out is None:
return numpy.zeros(shape, dtype)
if isinstance(out, str) and out[:6] == 'memmap':
import tempfile # noqa: delay import
tempdir = out[7:] if len(out) > 7 else None
if suffix is None:
suffix = '.memmap'
with tempfile.NamedTemporaryFile(dir=... | def create_output(out, shape, dtype, mode='w+', suffix=None) | Return numpy array where image data of shape and dtype can be copied.
The 'out' parameter may have the following values or types:
None
An empty array of shape and dtype is created and returned.
numpy.ndarray
An existing writable array of compatible dtype and shape. A view of
the sa... | 2.578717 | 2.377028 | 1.08485 |
# TODO: pythonize this
i = len(string)
while i:
i -= 1
if 8 < byte2int(string[i]) < 127:
break
else:
i = -1
return string[:i+1] | def stripascii(string) | Return string truncated at last byte that is 7-bit ASCII.
Clean NULL separated and terminated TIFF strings.
>>> stripascii(b'string\\x00string\\n\\x01\\x00')
b'string\\x00string\\n'
>>> stripascii(b'\\x00')
b'' | 4.760025 | 5.30939 | 0.896529 |
value = value.strip().lower()
if value in true: # might raise UnicodeWarning/BytesWarning
return True
if value in false:
return False
raise TypeError() | def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')) | Return string as bool if possible, else raise TypeError.
>>> asbool(b' False ')
False | 5.952767 | 8.055298 | 0.738988 |
if types is None:
types = int, float, asbool, bytes2str
for typ in types:
try:
return typ(value)
except (ValueError, AttributeError, TypeError, UnicodeEncodeError):
pass
return value | def astype(value, types=None) | Return argument as one of types if possible.
>>> astype('42')
42
>>> astype('3.14')
3.14
>>> astype('True')
True
>>> astype(b'Neee-Wom')
'Neee-Wom' | 4.069699 | 4.709218 | 0.864199 |
if size < threshold:
return "%i B" % size
for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
size /= 1024.0
if size < threshold:
return "%.2f %s" % (size, unit)
return 'ginormous' | def format_size(size, threshold=1536) | Return file size as string from byte size.
>>> format_size(1234)
'1234 B'
>>> format_size(12345678901)
'11.50 GiB' | 2.376072 | 2.785848 | 0.852908 |
def sortkey(x):
return [(int(c) if c.isdigit() else c) for c in re.split(numbers, x)]
numbers = re.compile(r'(\d+)')
return sorted(iterable, key=sortkey) | def natural_sorted(iterable) | Return human sorted list of strings.
E.g. for sorting file names.
>>> natural_sorted(['f1', 'f2', 'f10'])
['f1', 'f2', 'f10'] | 2.887924 | 3.624975 | 0.796674 |
if epoch is None:
epoch = datetime.datetime.fromordinal(693594)
return epoch + datetime.timedelta(timestamp) | def excel_datetime(timestamp, epoch=None) | Return datetime object from timestamp in Excel serial format.
Convert LSM time stamps.
>>> excel_datetime(40237.029999999795)
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982) | 5.466341 | 7.079359 | 0.772152 |
if julianday <= 1721423:
# no datetime before year 1
return None
a = julianday + 1
if a > 2299160:
alpha = math.trunc((a - 1867216.25) / 36524.25)
a += 1 + alpha - alpha // 4
b = a + (1524 if a > 1721423 else 1158)
c = math.trunc((b - 122.1) / 365.25)
d = ma... | def julian_datetime(julianday, milisecond=0) | Return datetime from days since 1/1/4713 BC and ms since midnight.
Convert Julian dates according to MetaMorph.
>>> julian_datetime(2451576, 54362783)
datetime.datetime(2000, 2, 2, 15, 6, 2, 783) | 1.812856 | 1.842062 | 0.984145 |
if byteorder in ('=', sys.byteorder):
return True
keys = {'big': '>', 'little': '<'}
return keys.get(byteorder, byteorder) == keys[sys.byteorder] | def byteorder_isnative(byteorder) | Return if byteorder matches the system's byteorder.
>>> byteorder_isnative('=')
True | 4.087114 | 5.193568 | 0.786957 |
# TODO: subarrays
result = {}
for descr, value in zip(recarray.dtype.descr, recarray):
name, dtype = descr[:2]
if dtype[1] == 'S':
value = bytes2str(stripnull(value))
elif value.ndim < 2:
value = value.tolist()
result[name] = value
return resu... | def recarray2dict(recarray) | Return numpy.recarray as dict. | 4.199275 | 4.004047 | 1.048758 |
from xml.etree import cElementTree as etree # delayed import
at = tx = ''
if prefix:
at, tx = prefix
def astype(value):
# return value as int, float, bool, or str
for t in (int, float, asbool):
try:
return t(value)
except Exception:... | def xml2dict(xml, sanitize=True, prefix=None) | Return XML as dict.
>>> xml2dict('<?xml version="1.0" ?><root attr="name"><key>1</key></root>')
{'root': {'key': 1, 'attr': 'name'}} | 2.243936 | 2.308064 | 0.972216 |
size = len(bytestr)
if size < 1 or width < 2 or height < 1:
return ''
if height == 1:
addr = b''
bytesperline = min(modulo * (((width - len(addr)) // 4) // modulo),
size)
if bytesperline < 1:
return ''
nlines = 1
else:
... | def hexdump(bytestr, width=75, height=24, snipat=-2, modulo=2, ellipsis=None) | Return hexdump representation of byte string.
>>> hexdump(binascii.unhexlify('49492a00080000000e00fe0004000100'))
'49 49 2a 00 08 00 00 00 0e 00 fe 00 04 00 01 00 II*.............' | 2.718788 | 2.742707 | 0.991279 |
string = string.strip()
if not string:
return True
if sys.version_info[0] == 3:
try:
return string.isprintable()
except Exception:
pass
try:
return string.decode('utf-8').isprintable()
except Exception:
pass
els... | def isprintable(string) | Return if all characters in string are printable.
>>> isprintable('abc')
True
>>> isprintable(b'\01')
False | 1.995341 | 2.153161 | 0.926703 |
for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'),
('\t', ' '), (' ', ' ')):
string = string.replace(a, b)
if compact:
for a, b in (('\n', ' '), ('[ ', '['),
(' ', ' '), (' ', ' '), (' ', ' ')):
string = string.replace(a, b)
... | def clean_whitespace(string, compact=False) | Return string with compressed whitespace. | 2.241847 | 2.167037 | 1.034522 |
try:
from lxml import etree # delayed import
if not isinstance(xml, bytes):
xml = xml.encode('utf-8')
xml = etree.parse(io.BytesIO(xml))
xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
encoding=xml.docinfo.encoding)
... | def pformat_xml(xml) | Return pretty formatted XML. | 2.683853 | 2.563018 | 1.047146 |
if height is None or height < 1:
height = 1024
if width is None or width < 1:
width = 256
npopt = numpy.get_printoptions()
numpy.set_printoptions(threshold=100, linewidth=width)
if isinstance(arg, basestring):
if arg[:5].lower() in ('<?xml', b'<?xml'):
if i... | def pformat(arg, width=79, height=24, compact=True) | Return pretty formatted representation of object as string.
Whitespace might be altered. | 3.253898 | 3.288519 | 0.989472 |
if snipat is None:
snipat = 0.5
if ellipsis is None:
if isinstance(string, bytes):
ellipsis = b'...'
else:
ellipsis = u'\u2026' # does not print on win-py3.5
esize = len(ellipsis)
splitlines = string.splitlines()
# TODO: finish and test multilin... | def snipstr(string, width=79, snipat=None, ellipsis='...') | Return string cut to specified length.
>>> snipstr('abcdefghijklmnop', 8)
'abc...op' | 2.993403 | 3.112584 | 0.96171 |
try:
return enum(arg)
except Exception:
try:
return enum[arg.upper()]
except Exception:
raise ValueError('invalid argument %s' % arg) | def enumarg(enum, arg) | Return enum member from its name or value.
>>> enumarg(TIFF.PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2> | 3.21376 | 4.512946 | 0.71212 |
result = {}
for key in keys:
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
for key, value in keyvalues.items():
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
else:
result[key] = value
ret... | def parse_kwargs(kwargs, *keys, **keyvalues) | Return dict with keys from keys|keyvals and values from kwargs|keyvals.
Existing keys are deleted from kwargs.
>>> kwargs = {'one': 1, 'two': 2, 'four': 4}
>>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
>>> kwargs == {'one': 1}
True
>>> kwargs2 == {'two': 2, 'four': 4, '... | 1.552169 | 1.854174 | 0.837122 |
for key, value in keyvalues.items():
if key not in kwargs:
kwargs[key] = value | def update_kwargs(kwargs, **keyvalues) | Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True | 2.366514 | 3.222911 | 0.734279 |
import subprocess # noqa: delayed import
if ignore is None:
ignore = ['More than 50 IFDs']
if jhove is None:
jhove = 'jhove'
out = subprocess.check_output([jhove, filename, '-m', 'TIFF-hul'])
if b'ErrorMessage: ' in out:
for line in out.splitlines():
line = ... | def validate_jhove(filename, jhove=None, ignore=None) | Validate TIFF file using jhove -m TIFF-hul.
Raise ValueError if jhove outputs an error message unless the message
contains one of the strings in 'ignore'.
JHOVE does not support bigtiff or more than 50 IFDs.
See `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_ | 4.133649 | 2.717353 | 1.521204 |
verbose = print_ if verbose else nullfunc
if tile is None:
tile = (256, 256)
if binfile is None:
binfile = lsmfile
elif binfile.lower() == 'none':
binfile = None
if binfile:
binfile += '_(z%ic%iy%ix%i)_m%%ip%%it%%03iy%%ix%%i.bin'
verbose('\nOpening LSM fil... | def lsm2bin(lsmfile, binfile=None, tile=None, verbose=True) | Convert [MP]TZCYX LSM file to series of BIN files.
One BIN file containing 'ZCYX' data are created for each position, time,
and tile. The position, time, and tile indices are encoded at the end
of the filenames. | 3.350937 | 3.295988 | 1.016671 |
try:
from Tkinter import Tk
import tkFileDialog as filedialog
except ImportError:
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
root.update()
filenames = filedialog.askopenfilename(**kwargs)
root.destroy()
return filenames | def askopenfilename(**kwargs) | Return file name(s) from Tkinter's file open dialog. | 2.132154 | 2.016392 | 1.057411 |
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0):
return
colormapped = self._colormap is not None
if self._imagej:
isrgb = self._shape[-1] in (3, 4)
description = imagej_description(
... | def _write_image_description(self) | Write metadata to ImageDescription tag. | 3.321691 | 3.214975 | 1.033193 |
if not self._truncate:
self._write_remaining_pages()
self._write_image_description()
self._fh.close() | def close(self) | Write remaining pages and close file handle. | 12.393163 | 6.452166 | 1.920776 |
for tif in self._files.values():
tif.filehandle.close()
self._files = {} | def close(self) | Close open file handle(s). | 7.909054 | 7.093559 | 1.114963 |
if not self.pages:
return []
useframes = self.pages.useframes
keyframe = self.pages.keyframe.index
series = []
for name in ('lsm', 'ome', 'imagej', 'shaped', 'fluoview', 'sis',
'uniform', 'mdgel'):
if getattr(self, 'is_' + na... | def series(self) | Return related pages as TiffPageSeries.
Side effect: after calling this function, TiffFile.pages might contain
TiffPage and TiffFrame instances. | 6.213461 | 5.20033 | 1.194821 |
pages = self.pages
pages._clear(False)
pages.useframes = False
if pages.cache:
pages._load()
result = []
keys = []
series = {}
for page in pages:
if not page.shape or product(page.shape) == 0:
continue
... | def _series_generic(self) | Return image series in file.
A series is a sequence of TiffPages with the same hash. | 3.97617 | 3.508698 | 1.133232 |
page = self.pages[0]
shape = page.shape
axes = page.axes
dtype = page.dtype
validate = not (page.is_scanimage or page.is_nih)
pages = self.pages._getlist(validate=validate)
lenpages = len(pages)
if lenpages > 1:
shape = (lenpages,) + s... | def _series_uniform(self) | Return all images in file as single series. | 4.604425 | 4.301598 | 1.070399 |
pages = self.pages
pages.useframes = True
lenpages = len(pages)
def append_series(series, pages, axes, shape, reshape, name,
truncated):
page = pages[0]
if not axes:
shape = page.shape
axes = page... | def _series_shaped(self) | Return image series in "shaped" file. | 4.330946 | 4.195783 | 1.032214 |
# ImageJ's dimension order is always TZCYXS
# TODO: fix loading of color, composite, or palette images
pages = self.pages
pages.useframes = True
pages.keyframe = 0
page = pages[0]
ij = self.imagej_metadata
def is_hyperstack():
# Image... | def _series_imagej(self) | Return image series in ImageJ file. | 4.668735 | 4.626944 | 1.009032 |
pages = self.pages._getlist(validate=False)
mm = self.fluoview_metadata
mmhd = list(reversed(mm['Dimensions']))
axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
for i in mmhd if i[1] > 1)
shape = tuple(int(i[1]) for i in mmhd if i[1] > 1)
... | def _series_fluoview(self) | Return image series in FluoView file. | 7.769032 | 7.290095 | 1.065697 |
# only a single page, scaled according to metadata in second page
self.pages.useframes = False
self.pages.keyframe = 0
md = self.mdgel_metadata
if md['FileTag'] in (2, 128):
dtype = numpy.dtype('float32')
scale = md['ScalePixel']
scale... | def _series_mdgel(self) | Return image series in MD Gel file. | 8.017838 | 7.476061 | 1.072468 |
pages = self.pages._getlist(validate=False)
page = pages[0]
lenpages = len(pages)
md = self.sis_metadata
if 'shape' in md and 'axes' in md:
shape = md['shape'] + page.shape
axes = md['axes'] + page.axes
elif lenpages == 1:
shap... | def _series_sis(self) | Return image series in Olympus SIS file. | 4.931735 | 4.639999 | 1.062874 |
lsmi = self.lsm_metadata
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
if self.pages[0].photometric == 2: # RGB; more than one channel
axes = axes.replace('C', '').replace('XY', 'XYC')
if lsmi.get('DimensionP', 0) > 1:
axes += 'P'
if lsmi.get... | def _series_lsm(self) | Return main and thumbnail series in LSM file. | 4.077318 | 3.91756 | 1.04078 |
# cache all pages to preserve corrected values
pages = self.pages
pages.cache = True
pages.useframes = True
# use first and second page as keyframes
pages.keyframe = 1
pages.keyframe = 0
# load remaining pages as frames
pages._load(keyfram... | def _lsm_load_pages(self) | Load and fix all pages from LSM file. | 6.555911 | 6.305957 | 1.039638 |
if self.filehandle.size < 2**32:
return
pages = self.pages
npages = len(pages)
series = self.series[0]
axes = series.axes
# find positions
positions = 1
for i in 0, 1:
if series.axes[i] in 'PM':
positions ... | def _lsm_fix_strip_offsets(self) | Unwrap strip offsets for LSM files greater than 4 GB.
Each series and position require separate unwrapping (undocumented). | 4.471682 | 4.139403 | 1.080272 |
pages = self.pages
if pages[0].compression == 1:
return
# sort pages by first strip offset
pages = sorted(pages, key=lambda p: p._offsetscounts[0][0])
npages = len(pages) - 1
for i, page in enumerate(pages):
if page.index % 2:
... | def _lsm_fix_strip_bytecounts(self) | Set databytecounts to size of compressed data.
The StripByteCounts tag in LSM files contains the number of bytes
for the uncompressed data. | 3.94581 | 4.055129 | 0.973042 |
# TODO: this likely reads the second page from file
try:
ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
if ismdgel:
self.is_uniform = False
return ismdgel
except IndexError:
return False | def is_mdgel(self) | File has MD Gel format. | 6.99139 | 6.017278 | 1.161886 |
# the hashes of IFDs 0, 7, and -1 are the same
pages = self.pages
page = pages[0]
if page.is_scanimage or page.is_nih:
return True
try:
useframes = pages.useframes
pages.useframes = False
h = page.hash
for i in ... | def is_uniform(self) | Return if file contains a uniform series of pages. | 7.491936 | 6.740552 | 1.111472 |
# TODO: check other formats
return not (self.is_lsm or self.is_stk or self.is_imagej or
self.is_fluoview or self.is_micromanager) | def is_appendable(self) | Return if pages can be appended to file without corrupting. | 9.384501 | 9.068894 | 1.034801 |
if not self.is_shaped:
return None
return tuple(json_description_metadata(s.pages[0].is_shaped)
for s in self.series if s.kind.lower() == 'shaped') | def shaped_metadata(self) | Return tifffile metadata from JSON descriptions as dicts. | 10.776685 | 7.872504 | 1.368902 |
if not self.is_stk:
return None
page = self.pages[0]
tags = page.tags
result = {}
result['NumberPlanes'] = tags['UIC2tag'].count
if page.description:
result['PlaneDescriptions'] = page.description.split('\0')
# result['plane_de... | def stk_metadata(self) | Return STK metadata from UIC tags as dict. | 3.297953 | 3.051461 | 1.080778 |
if not self.is_imagej:
return None
page = self.pages[0]
result = imagej_description_metadata(page.is_imagej)
if 'IJMetadata' in page.tags:
try:
result.update(page.tags['IJMetadata'].value)
except Exception:
pass... | def imagej_metadata(self) | Return consolidated ImageJ metadata as dict. | 4.849207 | 4.364451 | 1.111069 |
if not self.is_fluoview:
return None
result = {}
page = self.pages[0]
result.update(page.tags['MM_Header'].value)
# TODO: read stamps from all pages
result['Stamp'] = page.tags['MM_Stamp'].value
# skip parsing image description; not reliable
... | def fluoview_metadata(self) | Return consolidated FluoView metadata as dict. | 5.96926 | 5.569489 | 1.071779 |
if not self.is_fei:
return None
tags = self.pages[0].tags
if 'FEI_SFEG' in tags:
return tags['FEI_SFEG'].value
if 'FEI_HELIOS' in tags:
return tags['FEI_HELIOS'].value
return None | def fei_metadata(self) | Return FEI metadata from SFEG or HELIOS tags as dict. | 3.925859 | 2.410841 | 1.628419 |
if not self.is_sis:
return None
tags = self.pages[0].tags
result = {}
try:
result.update(tags['OlympusINI'].value)
except Exception:
pass
try:
result.update(tags['OlympusSIS'].value)
except Exception:
... | def sis_metadata(self) | Return Olympus SIS metadata from SIS and INI tags as dict. | 4.859 | 3.123167 | 1.555793 |
for page in self.pages[:2]:
if 'MDFileTag' in page.tags:
tags = page.tags
break
else:
return None
result = {}
for code in range(33445, 33453):
name = TIFF.TAGS[code]
if name not in tags:
... | def mdgel_metadata(self) | Return consolidated metadata from MD GEL tags as dict. | 5.242773 | 4.826972 | 1.086141 |
if not self.is_micromanager:
return None
# from file header
result = read_micromanager_metadata(self._fh)
# from tag
result.update(self.pages[0].tags['MicroManagerMetadata'].value)
return result | def micromanager_metadata(self) | Return consolidated MicroManager metadata as dict. | 8.704974 | 7.671902 | 1.134657 |
if not self.is_scanimage:
return None
result = {}
try:
framedata, roidata = read_scanimage_metadata(self._fh)
result['FrameData'] = framedata
result.update(roidata)
except ValueError:
pass
# TODO: scanimage_arti... | def scanimage_metadata(self) | Return ScanImage non-varying frame and ROI metadata as dict. | 4.857808 | 4.269579 | 1.137772 |
value = bool(value)
if self._cache and not value:
self._clear()
self._cache = value | def cache(self, value) | Enable or disable caching of pages/frames. Clear cache if False. | 5.161411 | 4.341288 | 1.188912 |
index = int(index)
if index < 0:
index %= len(self)
if self._keyframe.index == index:
return
if index == 0:
self._keyframe = self.pages[0]
return
if self._indexed or index < len(self.pages):
page = self.pages[in... | def keyframe(self, index) | Set current keyframe. Load TiffPage from file if necessary. | 3.70197 | 3.137731 | 1.179824 |
if self._cached:
return
pages = self.pages
if not pages:
return
if not self._indexed:
self._seek(-1)
if not self._cache:
return
fh = self.parent.filehandle
if keyframe is not None:
keyframe = sel... | def _load(self, keyframe=True) | Read all remaining pages from file. | 4.664283 | 4.23854 | 1.100446 |
pages = self.pages
try:
if sys.version_info[0] == 2:
raise ValueError('not supported on Python 2')
if len(pages) > 1:
raise ValueError('pages already loaded')
page = pages[0]
bytecounts = page._offsetscounts[1]
... | def _load_virtual_frames(self) | Calculate virtual TiffFrames. | 4.968739 | 4.729563 | 1.05057 |
pages = self.pages
if not pages:
return
self._keyframe = pages[0]
if fully:
# delete all but first TiffPage/TiffFrame
for i, page in enumerate(pages[1:]):
if not isinstance(page, inttypes) and page.offset is not None:
... | def _clear(self, fully=True) | Delete all but first page from cache. Set keyframe to first page. | 4.394904 | 3.523795 | 1.247208 |
pages = self.pages
lenpages = len(pages)
if lenpages == 0:
raise IndexError('index out of range')
fh = self.parent.filehandle
if fh.closed:
raise ValueError('seek of closed file')
if self._indexed or 0 <= index < lenpages:
pa... | def _seek(self, index, maxpages=None) | Seek file to offset of page specified by index. | 3.265106 | 3.242334 | 1.007023 |
getitem = self._getitem
_useframes = self.useframes
if key is None:
key = iter(range(len(self)))
elif isinstance(key, Iterable):
key = iter(key)
elif isinstance(key, slice):
start, stop, _ = key.indices(2**31-1)
if not sel... | def _getlist(self, key=None, useframes=True, validate=True) | Return specified pages as list of TiffPages or TiffFrames.
The first item is a TiffPage, and is used as a keyframe for
following TiffFrames. | 3.542271 | 3.365875 | 1.052407 |
key = int(key)
pages = self.pages
if key < 0:
key %= len(self)
elif self._indexed and key >= len(pages):
raise IndexError('index out of range')
if key < len(pages):
page = pages[key]
if self._cache:
if not... | def _getitem(self, key, validate=False) | Return specified page from cache or file. | 3.423616 | 3.2186 | 1.063697 |
data = self.asarray(**kwargs)
self = self.keyframe # self or keyframe
photometric = self.photometric
PHOTOMETRIC = TIFF.PHOTOMETRIC
if photometric == PHOTOMETRIC.PALETTE:
colormap = self.colormap
if (colormap.shape[1] < 2**self.bitspersample or
... | def asrgb(self, uint8=False, alpha=None, colormap=None,
dmin=None, dmax=None, **kwargs) | Return image data as RGB(A).
Work in progress. | 3.118868 | 3.088274 | 1.009906 |
tags = []
for tag in self.tags.values():
code = tag.code
if not codes or code in codes:
tags.append((code, tag))
return tags | def _gettags(self, codes=None, lock=None) | Return list of (code, TiffTag). | 3.020835 | 2.318025 | 1.303194 |
return hash(
self._shape + (
self.tilewidth, self.tilelength, self.tiledepth,
self.bitspersample, self.fillorder, self.predictor,
self.extrasamples, self.photometric, self.compression,
self.planarconfig)) | def hash(self) | Return checksum to identify pages in same series. | 7.168508 | 6.002739 | 1.194206 |
if self.is_contiguous:
offset, bytecount = self.is_contiguous
return [offset], [bytecount]
if self.is_tiled:
return self.dataoffsets, self.databytecounts
return clean_offsetscounts(self.dataoffsets, self.databytecounts) | def _offsetscounts(self) | Return simplified offsets and bytecounts. | 5.040911 | 4.145882 | 1.215884 |
if (self.compression != 1
or self.bitspersample not in (8, 16, 32, 64)):
return None
if 'TileWidth' in self.tags:
if (self.imagewidth != self.tilewidth or
self.imagelength % self.tilelength or
self.tilewidth % 16 or... | def is_contiguous(self) | Return offset and size of contiguous data, else None.
Excludes prediction and fill_order. | 3.562299 | 3.458895 | 1.029895 |
return (self.is_contiguous and self.fillorder == 1 and
self.predictor == 1 and not self.is_subsampled) | def is_final(self) | Return if page's image data are stored in final form.
Excludes byte-swapping. | 13.652278 | 12.019451 | 1.135849 |
return (self.parent.filehandle.is_file and self.is_final and
# (self.bitspersample == 8 or self.parent.isnative) and
self.is_contiguous[0] % self.dtype.itemsize == 0) | def is_memmappable(self) | Return if page's image data in file can be memory-mapped. | 11.404817 | 9.693563 | 1.176535 |
return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name))) | def flags(self) | Return set of flags. | 13.643421 | 11.241555 | 1.21366 |
if not self.is_andor:
return None
tags = self.tags
result = {'Id': tags['AndorId'].value}
for tag in list(self.tags.values()):
code = tag.code
if not 4864 < code < 5031:
continue
value = tag.value
name =... | def andor_tags(self) | Return consolidated metadata from Andor tags as dict.
Remove Andor tags from self.tags. | 4.442435 | 3.953339 | 1.123717 |
if not self.is_epics:
return None
result = {}
tags = self.tags
for tag in list(self.tags.values()):
code = tag.code
if not 65000 <= code < 65500:
continue
value = tag.value
if code == 65000:
... | def epics_tags(self) | Return consolidated metadata from EPICS areaDetector tags as dict.
Remove areaDetector tags from self.tags. | 3.01889 | 2.931667 | 1.029752 |
if not self.is_ndpi:
return None
tags = self.tags
result = {}
for name in ('Make', 'Model', 'Software'):
result[name] = tags[name].value
for code, name in TIFF.NDPI_TAGS.items():
code = str(code)
if code in tags:
... | def ndpi_tags(self) | Return consolidated metadata from Hamamatsu NDPI as dict. | 3.645453 | 3.596258 | 1.01368 |
for description in (self.description, self.description1):
if not description:
return None
if description[:7] == 'ImageJ=':
return description
return None | def is_imagej(self) | Return ImageJ description if exists, else None. | 6.155013 | 4.020949 | 1.530736 |
for description in (self.description, self.description1):
if not description:
return None
if description[:1] == '{' and '"shape":' in description:
return description
if description[:6] == 'shape=':
return description
... | def is_shaped(self) | Return description containing array shape if exists, else None. | 5.507702 | 4.01004 | 1.373478 |
if self.index > 1 or self.software != 'MetaSeries':
return False
d = self.description
return d.startswith('<MetaData>') and d.endswith('</MetaData>') | def is_metaseries(self) | Page contains MDS MetaSeries metadata in ImageDescription tag. | 8.84003 | 6.833648 | 1.293603 |
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</OME>' | def is_ome(self) | Page contains OME-XML in ImageDescription tag. | 8.324027 | 6.132229 | 1.357423 |
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</scn>' | def is_scn(self) | Page contains Leica SCN XML in ImageDescription tag. | 8.388301 | 6.391961 | 1.31232 |
fh = self.parent.filehandle
tiff = self.parent.tiff
unpack = struct.unpack
lock = NullContext() if lock is None else lock
tags = []
with lock:
fh.seek(self.offset)
try:
tagno = unpack(tiff.tagnoformat, fh.read(tiff.tagnosi... | def _gettags(self, codes=None, lock=None) | Return list of (code, TiffTag) from file. | 3.654024 | 3.390756 | 1.077643 |
if self.offset is None:
raise ValueError('cannot return virtual frame as page.')
self.parent.filehandle.seek(self.offset)
return TiffPage(self.parent, index=self.index) | def aspage(self) | Return TiffPage from file. | 9.362496 | 6.392874 | 1.464521 |
# TODO: fix TypeError on Python 2
# "TypeError: unbound method asarray() must be called with TiffPage
# instance as first argument (got TiffFrame instance instead)"
if self._keyframe is None:
raise RuntimeError('keyframe not set')
kwargs['validate'] = Fal... | def asarray(self, *args, **kwargs) | Read image data from file and return as numpy array. | 7.494135 | 7.131034 | 1.050918 |
if self._keyframe is None:
raise RuntimeError('keyframe not set')
kwargs['validate'] = False
return TiffPage.asrgb(self, *args, **kwargs) | def asrgb(self, *args, **kwargs) | Read image data from file and return RGB image as numpy array. | 7.659596 | 7.153454 | 1.070755 |
if self._keyframe == keyframe:
return
if self._keyframe is not None:
raise RuntimeError('cannot reset keyframe')
if len(self._offsetscounts[0]) != len(keyframe.dataoffsets):
raise RuntimeError('incompatible keyframe')
if keyframe.is_tiled:
... | def keyframe(self, keyframe) | Set keyframe. | 4.798438 | 4.750334 | 1.010126 |
if self._keyframe is None:
raise RuntimeError('keyframe not set')
if self._keyframe.is_contiguous:
return self._offsetscounts[0][0], self._keyframe.is_contiguous[1]
return None | def is_contiguous(self) | Return offset and size of contiguous data, else None. | 8.737211 | 5.866526 | 1.489333 |
try:
return TIFF.TAGS[self.code]
except KeyError:
return str(self.code) | def name(self) | Return name of tag from TIFF.TAGS registry. | 7.985449 | 3.146209 | 2.538117 |
if self.code != 258 or self.count != 2:
return
# TODO: test this case; need example file
log.warning('TiffTag %i: correcting LSM bitspersample tag', self.code)
value = struct.pack('<HH', *self.value)
self.valueoffset = struct.unpack('<I', value)[0]
pa... | def _fix_lsm_bitspersample(self, parent) | Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag. | 6.165338 | 5.424237 | 1.136628 |
if self.parent:
result = self.parent.asarray(series=self, out=out)
if self.transform is not None:
result = self.transform(result)
return result
return None | def asarray(self, out=None) | Return image data from series of TIFF pages as numpy array. | 4.391841 | 3.91511 | 1.121767 |
if not self._pages:
return None
pos = 0
for page in self._pages:
if page is None:
return None
if not page.is_final:
return None
if not pos:
pos = page.is_contiguous[0] + page.is_contiguous[1... | def offset(self) | Return offset to series data in file, if any. | 3.819965 | 3.557093 | 1.073901 |
key = int(key)
if key < 0:
key %= self._len
if len(self._pages) == 1 and 0 < key < self._len:
index = self._pages[0].index
return self.parent.pages._getitem(index + key)
return self._pages[key] | def _getitem(self, key) | Return specified page of series from cache or file. | 4.242955 | 3.729313 | 1.137731 |
if file is not None:
if isinstance(file, int):
return self.imread(self.files[file], **kwargs)
return self.imread(file, **kwargs)
im = self.imread(self.files[0], **kwargs)
shape = self.shape + im.shape
result = create_output(out, shape, dt... | def asarray(self, file=None, out=None, **kwargs) | Read image data from files and return as numpy array.
The kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match. | 2.937755 | 2.913615 | 1.008285 |
if not self.pattern:
raise TiffSequence.ParseError('invalid pattern')
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
matches = pattern.findall(os.path.split(self.files[0])[-1])
if not matches:
raise TiffSequence.ParseError('pattern does no... | def _parse(self) | Get axes and shape from file names. | 3.139171 | 2.816524 | 1.114555 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.