large_image.tilesource package¶
Submodules¶
large_image.tilesource.base module¶
- class large_image.tilesource.base.FileTileSource(path, *args, **kwargs)[source]¶
Bases:
TileSource
Initialize the tile class. See the base class for other available parameters.
- Parameters
path – a filesystem path for the tile source.
- classmethod canRead(path, *args, **kwargs)[source]¶
Check if we can read the input. This takes the same parameters as __init__.
- Returns
True if this class can read the input. False if it cannot.
- class large_image.tilesource.base.TileSource(encoding='JPEG', jpegQuality=95, jpegSubsampling=0, tiffCompression='raw', edge=False, style=None, *args, **kwargs)[source]¶
Bases:
object
Initialize the tile class.
- Parameters
jpegQuality – when serving jpegs, use this quality.
jpegSubsampling – when serving jpegs, use this subsampling (0 is full chroma, 1 is half, 2 is quarter).
encoding – ‘JPEG’, ‘PNG’, ‘TIFF’, or ‘TILED’.
edge – False to leave edge tiles whole, True or ‘crop’ to crop edge tiles, otherwise, an #rrggbb color to fill edges.
tiffCompression – the compression format to use when encoding a TIFF.
style –
if None, use the default style for the file. Otherwise, this is a string with a json-encoded dictionary. The style can contain the following keys:
- band
if -1 or None, and if style is specified at all, the greyscale value is used. Otherwise, a 1-based numerical index into the channels of the image or a string that matches the interpretation of the band (‘red’, ‘green’, ‘blue’, ‘gray’, ‘alpha’). Note that ‘gray’ on an RGB or RGBA image will use the green band.
- frame
if specified, override the frame value for this band. When used as part of a bands list, this can be used to composite multiple frames together. It is most efficient if at least one band either doesn’t specify a frame parameter or specifies the same frame value as the primary query.
- framedelta
if specified and frame is not specified, override the frame value for this band by using the current frame plus this value.
- min
the value to map to the first palette value. Defaults to 0. ‘auto’ to use 0 if the reported minimum and maximum of the band are between [0, 255] or use the reported minimum otherwise. ‘min’ or ‘max’ to always uses the reported minimum or maximum. ‘full’ to always use 0.
- max
the value to map to the last palette value. Defaults to 255. ‘auto’ to use 0 if the reported minimum and maximum of the band are between [0, 255] or use the reported maximum otherwise. ‘min’ or ‘max’ to always uses the reported minimum or maximum. ‘full’ to use the maximum value of the base data type (either 1, 255, or 65535).
- palette
a list of two or more color strings, where color strings are of the form #RRGGBB, #RRGGBBAA, #RGB, #RGBA, or any string parseable by the PIL modules, or, if it is installed, byt matplotlib. Alternately, this can be a single color, which implies [‘#000’, <color>], or the name of a palettable paletter or, if available, a matplotlib palette.
- nodata
the value to use for missing data. null or unset to not use a nodata value.
- composite
either ‘lighten’ or ‘multiply’. Defaults to ‘lighten’ for all except the alpha band.
- clamp
either True to clamp (also called clip or crop) values outside of the [min, max] to the ends of the palette or False to make outside values transparent.
- dtype
convert the results to the specified numpy dtype. Normally, if a style is applied, the results are intermediately a float numpy array with a value range of [0,255]. If this is ‘uint16’, it will be cast to that and multiplied by 65535/255. If ‘float’, it will be divided by 255.
- axis
keep only the specified axis from the numpy intermediate results. This can be used to extract a single channel after compositing.
Alternately, the style object can contain a single key of ‘bands’, which has a value which is a list of style dictionaries as above, excepting that each must have a band that is not -1. Bands are composited in the order listed. This base object may also contain the ‘dtype’ and ‘axis’ values.
- classmethod canRead(*args, **kwargs)[source]¶
Check if we can read the input. This takes the same parameters as __init__.
- Returns
True if this class can read the input. False if it cannot.
- convertRegionScale(sourceRegion, sourceScale=None, targetScale=None, targetUnits=None, cropToImage=True)[source]¶
Convert a region from one scale to another.
- Parameters
sourceRegion –
a dictionary of optional values which specify the part of an image to process.
- left
the left edge (inclusive) of the region to process.
- top
the top edge (inclusive) of the region to process.
- right
the right edge (exclusive) of the region to process.
- bottom
the bottom edge (exclusive) of the region to process.
- width
the width of the region to process.
- height
the height of the region to process.
- units
either ‘base_pixels’ (default), ‘pixels’, ‘mm’, or ‘fraction’. base_pixels are in maximum resolution pixels. pixels is in the specified magnification pixels. mm is in the specified magnification scale. fraction is a scale of 0 to 1. pixels and mm are only available if the magnification and mm per pixel are defined for the image.
sourceScale –
a dictionary of optional values which specify the scale of the source region. Required if the sourceRegion is in “mag_pixels” units.
- magnification
the magnification ratio.
- mm_x
the horizontal size of a pixel in millimeters.
- mm_y
the vertical size of a pixel in millimeters.
targetScale –
a dictionary of optional values which specify the scale of the target region. Required in targetUnits is in “mag_pixels” units.
- magnification
the magnification ratio.
- mm_x
the horizontal size of a pixel in millimeters.
- mm_y
the vertical size of a pixel in millimeters.
targetUnits – if not None, convert the region to these units. Otherwise, the units are will either be the sourceRegion units if those are not “mag_pixels” or base_pixels. If “mag_pixels”, the targetScale must be specified.
cropToImage – if True, don’t return region coordinates outside of the image.
- extensions = {None: 8}¶
A dictionary of known file extensions and the
SourcePriority
given to each. It must contain a None key with a priority for the tile source when the extension does not match.
- geospatial = False¶
- getAssociatedImage(imageKey, *args, **kwargs)[source]¶
Return an associated image.
- Parameters
imageKey – the key of the associated image to retrieve.
kwargs – optional arguments. Some options are width, height, encoding, jpegQuality, jpegSubsampling, and tiffCompression.
- Returns
imageData, imageMime: the image data and the mime type, or None if the associated image doesn’t exist.
- getAssociatedImagesList()[source]¶
Return a list of associated images.
- Returns
the list of image keys.
- getBandInformation(statistics=False, **kwargs)[source]¶
Get information about each band in the image.
- Parameters
statistics – if True, compute statistics if they don’t already exist.
- Returns
a dictionary of one dictionary per band. Each dictionary contains known values such as interpretation, min, max, mean, stdev.
- getInternalMetadata(**kwargs)[source]¶
Return additional known metadata about the tile source. Data returned from this method is not guaranteed to be in any particular format or have specific values.
- Returns
a dictionary of data or None.
- static getLRUHash(*args, **kwargs)[source]¶
Return a string hash used as a key in the recently-used cache for tile sources.
- Returns
a string hash value.
- getLevelForMagnification(magnification=None, exact=False, mm_x=None, mm_y=None, rounding='round', **kwargs)[source]¶
Get the level for a specific magnification or pixel size. If the magnification is unknown or no level is sufficient resolution, and an exact match is not requested, the highest level will be returned.
If none of magnification, mm_x, and mm_y are specified, the maximum level is returned. If more than one of these values is given, an average of those given will be used (exact will require all of them to match).
- Parameters
magnification – the magnification ratio.
exact – if True, only a level that matches exactly will be returned.
mm_x – the horizontal size of a pixel in millimeters.
mm_y – the vertical size of a pixel in millimeters.
rounding – if False, a fractional level may be returned. If ‘ceil’ or ‘round’, that function is used to convert the level to an integer (the exact flag still applies). If None, the level is not cropped to the actual image’s level range.
- Returns
the selected level or None for no match.
- getMagnificationForLevel(level=None)[source]¶
Get the magnification at a particular level.
- Parameters
level – None to use the maximum level, otherwise the level to get the magnification factor of.
- Returns
magnification, width of a pixel in mm, height of a pixel in mm.
- getMetadata()[source]¶
Return metadata about this tile source. This contains
- levels
number of tile levels in this image.
- sizeX
width of the image in pixels.
- sizeY
height of the image in pixels.
- tileWidth
width of a tile in pixels.
- tileHeight
height of a tile in pixels.
- magnification
if known, the magnificaiton of the image.
- mm_x
if known, the width of a pixel in millimeters.
- mm_y
if known, the height of a pixel in millimeters.
In addition to the keys that listed above, tile sources that expose multiple frames will also contain
- frames
a list of frames. Each frame entry is a dictionary with
- Frame
a 0-values frame index (the location in the list)
- Channel
optional. The name of the channel, if known
- IndexC
optional if unique. A 0-based index into the channel list
- IndexT
optional if unique. A 0-based index for time values
- IndexZ
optional if unique. A 0-based index for z values
- IndexXY
optional if unique. A 0-based index for view (xy) values
- Index
a 0-based index of non-channel unique sets. If the frames vary only by channel and are adjacent, they will have the same index.
- IndexRange
a dictionary of the number of unique index values from frames if greater than 1 (e.g., if an entry like IndexXY is not present, then all frames either do not have that value or have a value of 0).
- channels
optional. If known, a list of channel names
- channelmap
optional. If known, a dictionary of channel names with their offset into the channel list.
Note that this does nto include band information, though some tile sources may do so.
- getNativeMagnification()[source]¶
Get the magnification for the highest-resolution level.
- Returns
magnification, width of a pixel in mm, height of a pixel in mm.
- getOneBandInformation(band)[source]¶
Get band information for a single band.
- Parameters
band – a 1-based band.
- Returns
a dictionary of band information. See getBandInformation.
- getPixel(includeTileRecord=False, **kwargs)[source]¶
Get a single pixel from the current tile source.
- Parameters
includeTileRecord – if True, include the tile used for computing the pixel in the response.
kwargs – optional arguments. Some options are region, output, encoding, jpegQuality, jpegSubsampling, tiffCompression, fill. See tileIterator.
- Returns
a dictionary with the value of the pixel for each channel on a scale of [0-255], including alpha, if available. This may contain additional information.
- getPointAtAnotherScale(point, sourceScale=None, sourceUnits=None, targetScale=None, targetUnits=None, **kwargs)[source]¶
Given a point as a (x, y) tuple, convert it from one scale to another. The sourceScale, sourceUnits, targetScale, and targetUnits parameters are the same as convertRegionScale, where sourceUnits are the units used with sourceScale.
- getPreferredLevel(level)[source]¶
Given a desired level (0 is minimum resolution, self.levels - 1 is max resolution), return the level that contains actual data that is no lower resolution.
- Parameters
level – desired level
- Returns level
a level with actual data that is no lower resolution.
- getRegion(format=('image',), **kwargs)[source]¶
Get a rectangular region from the current tile source. Aspect ratio is preserved. If neither width nor height is given, the original size of the highest resolution level is used. If both are given, the returned image will be no larger than either size.
- Parameters
format – the desired format or a tuple of allowed formats. Formats are members of (TILE_FORMAT_PIL, TILE_FORMAT_NUMPY, TILE_FORMAT_IMAGE). If TILE_FORMAT_IMAGE, encoding may be specified.
kwargs – optional arguments. Some options are region, output, encoding, jpegQuality, jpegSubsampling, tiffCompression, fill. See tileIterator.
- Returns
regionData, formatOrRegionMime: the image data and either the mime type, if the format is TILE_FORMAT_IMAGE, or the format.
- getRegionAtAnotherScale(sourceRegion, sourceScale=None, targetScale=None, targetUnits=None, **kwargs)[source]¶
This takes the same parameters and returns the same results as getRegion, except instead of region and scale, it takes sourceRegion, sourceScale, targetScale, and targetUnits. These parameters are the same as convertRegionScale. See those two functions for parameter definitions.
- getSingleTile(*args, **kwargs)[source]¶
Return any single tile from an iterator. This takes exactly the same parameters as tileIterator. Use tile_position to get a specific tile, otherwise the first tile is returned.
- Returns
a tile dictionary or None.
- getSingleTileAtAnotherScale(*args, **kwargs)[source]¶
Return any single tile from a rescaled iterator. This takes exactly the same parameters as tileIteratorAtAnotherScale. Use tile_position to get a specific tile, otherwise the first tile is returned.
- Returns
a tile dictionary or None.
- getState()[source]¶
Return a string reflecting the state of the tile source. This is used as part of a cache key when hashing function return values.
- Returns
a string hash value of the source state.
- getThumbnail(width=None, height=None, **kwargs)[source]¶
Get a basic thumbnail from the current tile source. Aspect ratio is preserved. If neither width nor height is given, a default value is used. If both are given, the thumbnail will be no larger than either size. A thumbnail has the same options as a region except that it always includes the entire image and has a default size of 256 x 256.
- Parameters
width – maximum width in pixels.
height – maximum height in pixels.
kwargs – optional arguments. Some options are encoding, jpegQuality, jpegSubsampling, and tiffCompression.
- Returns
thumbData, thumbMime: the image data and the mime type.
- getTile(x, y, z, pilImageAllowed=False, numpyAllowed=False, sparseFallback=False, frame=None)[source]¶
Get a tile from a tile source, returning it as an binary image, a PIL image, or a numpy array.
- Parameters
x – the 0-based x position of the tile on the specified z level. 0 is left.
y – the 0-based y position of the tile on the specified z level. 0 is top.
z – the z level of the tile. May range from [0, self.levels], where 0 is the lowest resolution, single tile for the whole source.
pilImageAllowed – True if a PIL image may be returned.
numpyAllowed – True if a numpy image may be returned. ‘always’ to return a numpy array.
sparseFallback – if False and a tile doesn’t exist, raise an error. If True, check if a lower resolution tile exists, and, if so, interpolate the needed data for this tile.
frame – the frame number within the tile source. None is the same as 0 for multi-frame sources.
- Returns
either a numpy array, a PIL image, or a memory object with an image file.
- getTileCount(*args, **kwargs)[source]¶
Return the number of tiles that the tileIterator will return. See tileIterator for parameters.
- Returns
the number of tiles that the tileIterator will yield.
- getTileMimeType()[source]¶
Return the default mimetype for image tiles.
- Returns
the mime type of the tile.
- histogram(dtype=None, onlyMinMax=False, bins=256, density=False, format=None, *args, **kwargs)[source]¶
Get a histogram for a region.
- Parameters
dtype – if specified, the tiles must be this numpy.dtype.
onlyMinMax – if True, only return the minimum and maximum value of the region.
bins – the number of bins in the histogram. This is passed to numpy.histogram, but needs to produce the same set of edges for each tile.
density – if True, scale the results based on the number of samples.
format – ignored. Used to override the format for the tileIterator.
range – if None, use the computed min and (max + 1). Otherwise, this is the range passed to numpy.histogram. Note this is only accessible via kwargs as it otherwise overloads the range function.
args – parameters to pass to the tileIterator.
kwargs – parameters to pass to the tileIterator.
- Returns
if onlyMinMax is true, this is a dictionary with keys min and max, each of which is a numpy array with the minimum and maximum of all of the bands. If onlyMinMax is False, this is a dictionary with a single key ‘histogram’ that contains a list of histograms per band. Each entry is a dictionary with min, max, range, hist, and bin_edges. range is [min, (max + 1)]. hist is the counts (normalized if density is True) for each bin. bin_edges is an array one longer than the hist array that contains the boundaries between bins.
- mimeTypes = {None: 8}¶
A dictionary of common mime-types handled by the source and the
SourcePriority
given to each. This are used in place of or in additional to extensions.
- name = None¶
Name of the tile source
- tileFrames(format=('image',), frameList=None, framesAcross=None, **kwargs)[source]¶
Given the parameters for getRegion, plus a list of frames and the number of frames across, make a larger image composed of a region from each listed frame composited together.
- Parameters
format – the desired format or a tuple of allowed formats. Formats are members of (TILE_FORMAT_PIL, TILE_FORMAT_NUMPY, TILE_FORMAT_IMAGE). If TILE_FORMAT_IMAGE, encoding may be specified.
frameList – None for all frames, or a list of 0-based integers.
framesAcross – the number of frames across the final image. If unspecified, this is the ceiling of sqrt(number of frames in frame list).
kwargs – optional arguments. Some options are region, output, encoding, jpegQuality, jpegSubsampling, tiffCompression, fill. See tileIterator.
- Returns
regionData, formatOrRegionMime: the image data and either the mime type, if the format is TILE_FORMAT_IMAGE, or the format.
- tileIterator(format=('numpy',), resample=True, **kwargs)[source]¶
Iterate on all tiles in the specified region at the specified scale. Each tile is returned as part of a dictionary that includes
- x, y
(left, top) coordinates in current magnification pixels
- width, height
size of current tile in current magnification pixels
- tile
cropped tile image
- format
format of the tile
- level
level of the current tile
- level_x, level_y
the tile reference number within the level. Tiles are numbered (0, 0), (1, 0), (2, 0), etc. The 0th tile yielded may not be (0, 0) if a region is specified.
- tile_position
a dictionary of the tile position within the iterator, containing:
- level_x, level_y
the tile reference number within the level.
- region_x, region_y
0, 0 is the first tile in the full iteration (when not restricting the iteration to a single tile).
- position
a 0-based value for the tile within the full iteration.
- iterator_range
a dictionary of the output range of the iterator:
- level_x_min, level_x_max
the tiles that are be included during the full iteration: [layer_x_min, layer_x_max).
- level_y_min, level_y_max
the tiles that are be included during the full iteration: [layer_y_min, layer_y_max).
- region_x_max, region_y_max
the number of tiles included during the full iteration. This is layer_x_max - layer_x_min, layer_y_max - layer_y_min.
- position
the total number of tiles included in the full iteration. This is region_x_max * region_y_max.
- magnification
magnification of the current tile
- mm_x, mm_y
size of the current tile pixel in millimeters.
- gx, gy
(left, top) coordinates in maximum-resolution pixels
- gwidth, gheight
size of of the current tile in maximum-resolution pixels.
- tile_overlap
the amount of overlap with neighboring tiles (left, top, right, and bottom). Overlap never extends outside of the requested region.
If a region that includes partial tiles is requested, those tiles are cropped appropriately. Most images will have tiles that get cropped along the right and bottom edges in any case. If an exact magnification or scale is requested, no tiles will be returned.
- Parameters
format – the desired format or a tuple of allowed formats. Formats are members of (TILE_FORMAT_PIL, TILE_FORMAT_NUMPY, TILE_FORMAT_IMAGE). If TILE_FORMAT_IMAGE, encoding must be specified.
resample –
If True or one of PIL.Image.Resampling.NEAREST, LANCZOS, BILINEAR, or BICUBIC to resample tiles that are not the target output size. Tiles that are resampled will have additional dictionary entries of:
- scaled
the scaling factor that was applied (less than 1 is downsampled).
- tile_x, tile_y
(left, top) coordinates before scaling
- tile_width, tile_height
size of the current tile before scaling.
- tile_magnification
magnification of the current tile before scaling.
- tile_mm_x, tile_mm_y
size of a pixel in a tile in millimeters before scaling.
Note that scipy.misc.imresize uses PIL internally.
region –
a dictionary of optional values which specify the part of the image to process:
- left
the left edge (inclusive) of the region to process.
- top
the top edge (inclusive) of the region to process.
- right
the right edge (exclusive) of the region to process.
- bottom
the bottom edge (exclusive) of the region to process.
- width
the width of the region to process.
- height
the height of the region to process.
- units
either ‘base_pixels’ (default), ‘pixels’, ‘mm’, or ‘fraction’. base_pixels are in maximum resolution pixels. pixels is in the specified magnification pixels. mm is in the specified magnification scale. fraction is a scale of 0 to 1. pixels and mm are only available if the magnification and mm per pixel are defined for the image.
output –
a dictionary of optional values which specify the size of the output.
- maxWidth
maximum width in pixels. If either maxWidth or maxHeight is specified, magnification, mm_x, and mm_y are ignored.
- maxHeight
maximum height in pixels.
scale –
a dictionary of optional values which specify the scale of the region and / or output. This applies to region if pixels or mm are used for inits. It applies to output if neither output maxWidth nor maxHeight is specified.
- magnification
the magnification ratio. Only used is maxWidth and maxHeight are not specified or None.
- mm_x
the horizontal size of a pixel in millimeters.
- mm_y
the vertical size of a pixel in millimeters.
- exact
if True, only a level that matches exactly will be returned. This is only applied if magnification, mm_x, or mm_y is used.
tile_position – if present, either a number to only yield the (tile_position)th tile [0 to (xmax - min) * (ymax - ymin)) that the iterator would yield, or a dictionary of {region_x, region_y} to yield that tile, where 0, 0 is the first tile yielded, and xmax - xmin - 1, ymax - ymin - 1 is the last tile yielded, or a dictionary of {level_x, level_y} to yield that specific tile if it is in the region.
tile_size –
if present, retile the output to the specified tile size. If only width or only height is specified, the resultant tiles will be square. This is a dictionary containing at least one of:
- width
the desired tile width.
- height
the desired tile height.
tile_overlap –
if present, retile the output adding a symmetric overlap to the tiles. If either x or y is not specified, it defaults to zero. The overlap does not change the tile size, only the stride of the tiles. This is a dictionary containing:
- x
the horizontal overlap in pixels.
- y
the vertical overlap in pixels.
- edges
if True, then the edge tiles will exclude the overlap distance. If unset or False, the edge tiles are full size.
The overlap is conceptually split between the two sides of the tile. This is only relevant to where overlap is reported or if edges is True
As an example, suppose an image that is 8 pixels across (01234567) and a tile size of 5 is requested with an overlap of 4. If the edges option is False (the default), the following tiles are returned: 01234, 12345, 23456, 34567. Each tile reports its overlap, and the non-overlapped area of each tile is 012, 3, 4, 567. If the edges option is True, the tiles returned are: 012, 0123, 01234, 12345, 23456, 34567, 4567, 567, with the non-overlapped area of each as 0, 1, 2, 3, 4, 5, 6, 7.
encoding – if format includes TILE_FORMAT_IMAGE, a valid PIL encoding (typically ‘PNG’, ‘JPEG’, or ‘TIFF’) or ‘TILED’ (identical to TIFF). Must also be in the TileOutputMimeTypes map.
jpegQuality – the quality to use when encoding a JPEG.
jpegSubsampling – the subsampling level to use when encoding a JPEG.
tiffCompression – the compression format when encoding a TIFF. This is usually ‘raw’, ‘tiff_lzw’, ‘jpeg’, or ‘tiff_adobe_deflate’. Some of these are aliased: ‘none’, ‘lzw’, ‘deflate’.
frame – the frame number within the tile source. None is the same as 0 for multi-frame sources.
kwargs – optional arguments.
- Yields
an iterator that returns a dictionary as listed above.
- tileIteratorAtAnotherScale(sourceRegion, sourceScale=None, targetScale=None, targetUnits=None, **kwargs)[source]¶
This takes the same parameters and returns the same results as tileIterator, except instead of region and scale, it takes sourceRegion, sourceScale, targetScale, and targetUnits. These parameters are the same as convertRegionScale. See those two functions for parameter definitions.
large_image.tilesource.tiledict module¶
- class large_image.tilesource.tiledict.LazyTileDict(tileInfo, *args, **kwargs)[source]¶
Bases:
dict
Tiles returned from the tile iterator and dictionaries of information with actual image data in the ‘tile’ key and the format in the ‘format’ key. Since some applications need information about the tile but don’t need the image data, these two values are lazily computed. The LazyTileDict can be treated like a regular dictionary, except that when either of those two keys are first accessed, they will cause the image to be loaded and possibly converted to a PIL image and cropped.
Unless setFormat is called on the tile, tile images may always be returned as PIL images.
Create a LazyTileDict dictionary where there is enough information to load the tile image. ang and kwargs are as for the dict() class.
- Parameters
tileInfo – a dictionary of x, y, level, format, encoding, crop, and source, used for fetching the tile image.
- release()[source]¶
If the tile has been loaded, unload it. It can be loaded again. This is useful if you want to keep tiles available in memory but not their actual tile data.
- setFormat(format, resample=False, imageKwargs=None)[source]¶
Set a more restrictive output format for a tile, possibly also resizing it via resampling. If this is not called, the tile may either be returned as one of the specified formats or as a PIL image.
- Parameters
format – a tuple or list of allowed formats. Formats are members of TILE_FORMAT_*. This will avoid converting images if they are in the desired output encoding (regardless of subparameters).
resample – if not False or None, allow resampling. Once turned on, this cannot be turned off on the tile.
imageKwargs – additional parameters that should be passed to _encodeImage.
large_image.tilesource.utilities module¶
- class large_image.tilesource.utilities.ImageBytes(source: bytes, mimetype: Optional[str] = None)[source]¶
Bases:
bytes
Wrapper class to make repr of image bytes better in ipython.
- property mimetype¶
- large_image.tilesource.utilities.addPILFormatsToOutputOptions()[source]¶
Check PIL for available formats that be saved and add them to the lists of of available formats.
- large_image.tilesource.utilities.dictToEtree(d, root=None)[source]¶
Convert a dictionary in the style produced by etreeToDict back to an etree. Make an xml string via xml.etree.ElementTree.tostring(dictToEtree( dictionary), encoding=’utf8’, method=’xml’). Note that this function and etreeToDict are not perfect conversions; numerical values are quoted in xml. Plain key-value pairs are ambiguous whether they should be attributes or text values. Text fields are collected together.
- Parameters
d – a dictionary.
- Prarm root
the root node to attach this dictionary to.
- Returns
an etree.
- large_image.tilesource.utilities.etreeToDict(t)[source]¶
Convert an xml etree to a nested dictionary without schema names in the keys. If you have an xml string, this can be converted to a dictionary via xml.etree.etreeToDict(ElementTree.fromstring(xml_string)).
- Parameters
t – an etree.
- Returns
a python dictionary with the results.
- large_image.tilesource.utilities.getAvailableNamedPalettes(includeColors=True, reduced=False)[source]¶
Get a list of all named palettes that can be used with getPaletteColors.
- Parameters
includeColors – if True, include named colors. If False, only include actual palettes.
reduced – if True, exclude reversed palettes and palettes with fewer colors where a palette with the same basic name exists with more colors.
- Returns
a list of names.
- large_image.tilesource.utilities.getPaletteColors(value)[source]¶
Given a list or a name, return a list of colors in the form of a numpy array of RGBA. If a list, each entry is a color name resolvable by either PIL.ImageColor.getcolor, by matplotlib.colors, or a 3 or 4 element list or tuple of RGB(A) values on a scale of 0-1. If this is NOT a list, then, if it can be parsed as a color, it is treated as [‘#000’, <value>]. If that cannot be parsed, then it is assumed to be a named palette in palettable (such as viridis.Viridis_12) or a named palette in matplotlib (including plugins).
- Parameters
value – Either a list, a single color name, or a palette name. See above.
- Returns
a numpy array of RGBA value on the scale of [0-255].
- large_image.tilesource.utilities.getTileFramesQuadInfo(metadata, options=None)[source]¶
Compute what tile_frames need to be requested for a particular condition.
- Parameters
metadata – the tile source metadata. Needs to contain sizeX, sizeY, tileWidth, tileHeight, and a list of frames.
options –
dictionary of format: The compression and format for the texture. Defaults to
{‘encoding’: ‘JPEG’, ‘jpegQuality’: 85, ‘jpegSubsampling’: 1}.
- query: Additional query options to add to the tile source, such as
style.
- frameBase: (default 0) Starting frame number used. c/z/xy/z to step
through that index length (0 to 1 less than the value), which is probably only useful for cache reporting or scheduling.
- frameStride: (default 1) Only use every
frameStride
frame of the image. c/z/xy/z to use that axis length.
- frameGroup: (default 1) If above 1 and multiple textures are used, each
texture will have an even multiple of the group size number of frames. This helps control where texture loading transitions occur. c/z/xy/z to use that axis length.
- frameGroupFactor: (default 4) If
frameGroup
would reduce the size of the tile images beyond this factor, don’t use it.
- frameGroupStride: (default 1) If
frameGroup
is above 1 and multiple textures are used, then the frames are reordered based on this stride value. “auto” to use frameGroup / frameStride if that value is an integer.
- maxTextureSize: Limit the maximum texture size to a square of this
size.
- maxTextures: (default 1) If more than one, allow multiple textures to
increase the size of the individual frames. The number of textures will be capped by
maxTotalTexturePixels
as well as this number.- maxTotalTexturePixels: (default 1073741824) Limit the maximum texture
size and maximum number of textures so that the combined set does not exceed this number of pixels.
- alignment: (default 16) Individual frames are buffered to an alignment
of this maxy pixels. If JPEG compression is used, this should be 8 for monochrome images or jpegs without subsampling, or 16 for jpegs with moderate subsampling to avoid compression artifacts from leaking between frames.
- maxFrameSize: If set, limit the maximum width and height of an
individual frame to this value.
- Returns
a dictionary of values to use for making calls to tile_frames.
- large_image.tilesource.utilities.histogramThreshold(histogram, threshold, fromMax=False)[source]¶
Given a histogram and a threshold on a scale of [0, 1], return the bin edge that excludes no more than the specified threshold amount of values. For instance, a threshold of 0.02 would exclude at most 2% of the values.
- Parameters
histogram – a histogram record for a specific channel.
threshold – a value from 0 to 1.
fromMax – if False, return values excluding the low end of the histogram; if True, return values from excluding the high end of the histogram.
- Returns
the value the excludes no more than the threshold from the specified end.
- large_image.tilesource.utilities.isValidPalette(value)[source]¶
Check if a value can be used as a palette.
- Parameters
value – Either a list, a single color name, or a palette name. See getPaletteColors.
- Returns
a boolean; true if the value can be used as a palette.
- large_image.tilesource.utilities.nearPowerOfTwo(val1, val2, tolerance=0.02)[source]¶
Check if two values are different by nearly a power of two.
- Parameters
val1 – the first value to check.
val2 – the second value to check.
tolerance – the maximum difference in the log2 ratio’s mantissa.
- Returns
True if the valeus are nearly a power of two different from each other; false otherwise.
Module contents¶
- class large_image.tilesource.FileTileSource(path, *args, **kwargs)[source]¶
Bases:
TileSource
Initialize the tile class. See the base class for other available parameters.
- Parameters
path – a filesystem path for the tile source.
- classmethod canRead(path, *args, **kwargs)[source]¶
Check if we can read the input. This takes the same parameters as __init__.
- Returns
True if this class can read the input. False if it cannot.
- large_image.tilesource.TileGeneralException¶
alias of
TileGeneralError
- class large_image.tilesource.TileSource(encoding='JPEG', jpegQuality=95, jpegSubsampling=0, tiffCompression='raw', edge=False, style=None, *args, **kwargs)[source]¶
Bases:
object
Initialize the tile class.
- Parameters
jpegQuality – when serving jpegs, use this quality.
jpegSubsampling – when serving jpegs, use this subsampling (0 is full chroma, 1 is half, 2 is quarter).
encoding – ‘JPEG’, ‘PNG’, ‘TIFF’, or ‘TILED’.
edge – False to leave edge tiles whole, True or ‘crop’ to crop edge tiles, otherwise, an #rrggbb color to fill edges.
tiffCompression – the compression format to use when encoding a TIFF.
style –
if None, use the default style for the file. Otherwise, this is a string with a json-encoded dictionary. The style can contain the following keys:
- band
if -1 or None, and if style is specified at all, the greyscale value is used. Otherwise, a 1-based numerical index into the channels of the image or a string that matches the interpretation of the band (‘red’, ‘green’, ‘blue’, ‘gray’, ‘alpha’). Note that ‘gray’ on an RGB or RGBA image will use the green band.
- frame
if specified, override the frame value for this band. When used as part of a bands list, this can be used to composite multiple frames together. It is most efficient if at least one band either doesn’t specify a frame parameter or specifies the same frame value as the primary query.
- framedelta
if specified and frame is not specified, override the frame value for this band by using the current frame plus this value.
- min
the value to map to the first palette value. Defaults to 0. ‘auto’ to use 0 if the reported minimum and maximum of the band are between [0, 255] or use the reported minimum otherwise. ‘min’ or ‘max’ to always uses the reported minimum or maximum. ‘full’ to always use 0.
- max
the value to map to the last palette value. Defaults to 255. ‘auto’ to use 0 if the reported minimum and maximum of the band are between [0, 255] or use the reported maximum otherwise. ‘min’ or ‘max’ to always uses the reported minimum or maximum. ‘full’ to use the maximum value of the base data type (either 1, 255, or 65535).
- palette
a list of two or more color strings, where color strings are of the form #RRGGBB, #RRGGBBAA, #RGB, #RGBA, or any string parseable by the PIL modules, or, if it is installed, byt matplotlib. Alternately, this can be a single color, which implies [‘#000’, <color>], or the name of a palettable paletter or, if available, a matplotlib palette.
- nodata
the value to use for missing data. null or unset to not use a nodata value.
- composite
either ‘lighten’ or ‘multiply’. Defaults to ‘lighten’ for all except the alpha band.
- clamp
either True to clamp (also called clip or crop) values outside of the [min, max] to the ends of the palette or False to make outside values transparent.
- dtype
convert the results to the specified numpy dtype. Normally, if a style is applied, the results are intermediately a float numpy array with a value range of [0,255]. If this is ‘uint16’, it will be cast to that and multiplied by 65535/255. If ‘float’, it will be divided by 255.
- axis
keep only the specified axis from the numpy intermediate results. This can be used to extract a single channel after compositing.
Alternately, the style object can contain a single key of ‘bands’, which has a value which is a list of style dictionaries as above, excepting that each must have a band that is not -1. Bands are composited in the order listed. This base object may also contain the ‘dtype’ and ‘axis’ values.
- classmethod canRead(*args, **kwargs)[source]¶
Check if we can read the input. This takes the same parameters as __init__.
- Returns
True if this class can read the input. False if it cannot.
- convertRegionScale(sourceRegion, sourceScale=None, targetScale=None, targetUnits=None, cropToImage=True)[source]¶
Convert a region from one scale to another.
- Parameters
sourceRegion –
a dictionary of optional values which specify the part of an image to process.
- left
the left edge (inclusive) of the region to process.
- top
the top edge (inclusive) of the region to process.
- right
the right edge (exclusive) of the region to process.
- bottom
the bottom edge (exclusive) of the region to process.
- width
the width of the region to process.
- height
the height of the region to process.
- units
either ‘base_pixels’ (default), ‘pixels’, ‘mm’, or ‘fraction’. base_pixels are in maximum resolution pixels. pixels is in the specified magnification pixels. mm is in the specified magnification scale. fraction is a scale of 0 to 1. pixels and mm are only available if the magnification and mm per pixel are defined for the image.
sourceScale –
a dictionary of optional values which specify the scale of the source region. Required if the sourceRegion is in “mag_pixels” units.
- magnification
the magnification ratio.
- mm_x
the horizontal size of a pixel in millimeters.
- mm_y
the vertical size of a pixel in millimeters.
targetScale –
a dictionary of optional values which specify the scale of the target region. Required in targetUnits is in “mag_pixels” units.
- magnification
the magnification ratio.
- mm_x
the horizontal size of a pixel in millimeters.
- mm_y
the vertical size of a pixel in millimeters.
targetUnits – if not None, convert the region to these units. Otherwise, the units are will either be the sourceRegion units if those are not “mag_pixels” or base_pixels. If “mag_pixels”, the targetScale must be specified.
cropToImage – if True, don’t return region coordinates outside of the image.
- extensions = {None: 8}¶
A dictionary of known file extensions and the
SourcePriority
given to each. It must contain a None key with a priority for the tile source when the extension does not match.
- geospatial = False¶
- getAssociatedImage(imageKey, *args, **kwargs)[source]¶
Return an associated image.
- Parameters
imageKey – the key of the associated image to retrieve.
kwargs – optional arguments. Some options are width, height, encoding, jpegQuality, jpegSubsampling, and tiffCompression.
- Returns
imageData, imageMime: the image data and the mime type, or None if the associated image doesn’t exist.
- getAssociatedImagesList()[source]¶
Return a list of associated images.
- Returns
the list of image keys.
- getBandInformation(statistics=False, **kwargs)[source]¶
Get information about each band in the image.
- Parameters
statistics – if True, compute statistics if they don’t already exist.
- Returns
a dictionary of one dictionary per band. Each dictionary contains known values such as interpretation, min, max, mean, stdev.
- getInternalMetadata(**kwargs)[source]¶
Return additional known metadata about the tile source. Data returned from this method is not guaranteed to be in any particular format or have specific values.
- Returns
a dictionary of data or None.
- static getLRUHash(*args, **kwargs)[source]¶
Return a string hash used as a key in the recently-used cache for tile sources.
- Returns
a string hash value.
- getLevelForMagnification(magnification=None, exact=False, mm_x=None, mm_y=None, rounding='round', **kwargs)[source]¶
Get the level for a specific magnification or pixel size. If the magnification is unknown or no level is sufficient resolution, and an exact match is not requested, the highest level will be returned.
If none of magnification, mm_x, and mm_y are specified, the maximum level is returned. If more than one of these values is given, an average of those given will be used (exact will require all of them to match).
- Parameters
magnification – the magnification ratio.
exact – if True, only a level that matches exactly will be returned.
mm_x – the horizontal size of a pixel in millimeters.
mm_y – the vertical size of a pixel in millimeters.
rounding – if False, a fractional level may be returned. If ‘ceil’ or ‘round’, that function is used to convert the level to an integer (the exact flag still applies). If None, the level is not cropped to the actual image’s level range.
- Returns
the selected level or None for no match.
- getMagnificationForLevel(level=None)[source]¶
Get the magnification at a particular level.
- Parameters
level – None to use the maximum level, otherwise the level to get the magnification factor of.
- Returns
magnification, width of a pixel in mm, height of a pixel in mm.
- getMetadata()[source]¶
Return metadata about this tile source. This contains
- levels
number of tile levels in this image.
- sizeX
width of the image in pixels.
- sizeY
height of the image in pixels.
- tileWidth
width of a tile in pixels.
- tileHeight
height of a tile in pixels.
- magnification
if known, the magnificaiton of the image.
- mm_x
if known, the width of a pixel in millimeters.
- mm_y
if known, the height of a pixel in millimeters.
In addition to the keys that listed above, tile sources that expose multiple frames will also contain
- frames
a list of frames. Each frame entry is a dictionary with
- Frame
a 0-values frame index (the location in the list)
- Channel
optional. The name of the channel, if known
- IndexC
optional if unique. A 0-based index into the channel list
- IndexT
optional if unique. A 0-based index for time values
- IndexZ
optional if unique. A 0-based index for z values
- IndexXY
optional if unique. A 0-based index for view (xy) values
- Index
a 0-based index of non-channel unique sets. If the frames vary only by channel and are adjacent, they will have the same index.
- IndexRange
a dictionary of the number of unique index values from frames if greater than 1 (e.g., if an entry like IndexXY is not present, then all frames either do not have that value or have a value of 0).
- channels
optional. If known, a list of channel names
- channelmap
optional. If known, a dictionary of channel names with their offset into the channel list.
Note that this does nto include band information, though some tile sources may do so.
- getNativeMagnification()[source]¶
Get the magnification for the highest-resolution level.
- Returns
magnification, width of a pixel in mm, height of a pixel in mm.
- getOneBandInformation(band)[source]¶
Get band information for a single band.
- Parameters
band – a 1-based band.
- Returns
a dictionary of band information. See getBandInformation.
- getPixel(includeTileRecord=False, **kwargs)[source]¶
Get a single pixel from the current tile source.
- Parameters
includeTileRecord – if True, include the tile used for computing the pixel in the response.
kwargs – optional arguments. Some options are region, output, encoding, jpegQuality, jpegSubsampling, tiffCompression, fill. See tileIterator.
- Returns
a dictionary with the value of the pixel for each channel on a scale of [0-255], including alpha, if available. This may contain additional information.
- getPointAtAnotherScale(point, sourceScale=None, sourceUnits=None, targetScale=None, targetUnits=None, **kwargs)[source]¶
Given a point as a (x, y) tuple, convert it from one scale to another. The sourceScale, sourceUnits, targetScale, and targetUnits parameters are the same as convertRegionScale, where sourceUnits are the units used with sourceScale.
- getPreferredLevel(level)[source]¶
Given a desired level (0 is minimum resolution, self.levels - 1 is max resolution), return the level that contains actual data that is no lower resolution.
- Parameters
level – desired level
- Returns level
a level with actual data that is no lower resolution.
- getRegion(format=('image',), **kwargs)[source]¶
Get a rectangular region from the current tile source. Aspect ratio is preserved. If neither width nor height is given, the original size of the highest resolution level is used. If both are given, the returned image will be no larger than either size.
- Parameters
format – the desired format or a tuple of allowed formats. Formats are members of (TILE_FORMAT_PIL, TILE_FORMAT_NUMPY, TILE_FORMAT_IMAGE). If TILE_FORMAT_IMAGE, encoding may be specified.
kwargs – optional arguments. Some options are region, output, encoding, jpegQuality, jpegSubsampling, tiffCompression, fill. See tileIterator.
- Returns
regionData, formatOrRegionMime: the image data and either the mime type, if the format is TILE_FORMAT_IMAGE, or the format.
- getRegionAtAnotherScale(sourceRegion, sourceScale=None, targetScale=None, targetUnits=None, **kwargs)[source]¶
This takes the same parameters and returns the same results as getRegion, except instead of region and scale, it takes sourceRegion, sourceScale, targetScale, and targetUnits. These parameters are the same as convertRegionScale. See those two functions for parameter definitions.
- getSingleTile(*args, **kwargs)[source]¶
Return any single tile from an iterator. This takes exactly the same parameters as tileIterator. Use tile_position to get a specific tile, otherwise the first tile is returned.
- Returns
a tile dictionary or None.
- getSingleTileAtAnotherScale(*args, **kwargs)[source]¶
Return any single tile from a rescaled iterator. This takes exactly the same parameters as tileIteratorAtAnotherScale. Use tile_position to get a specific tile, otherwise the first tile is returned.
- Returns
a tile dictionary or None.
- getState()[source]¶
Return a string reflecting the state of the tile source. This is used as part of a cache key when hashing function return values.
- Returns
a string hash value of the source state.
- getThumbnail(width=None, height=None, **kwargs)[source]¶
Get a basic thumbnail from the current tile source. Aspect ratio is preserved. If neither width nor height is given, a default value is used. If both are given, the thumbnail will be no larger than either size. A thumbnail has the same options as a region except that it always includes the entire image and has a default size of 256 x 256.
- Parameters
width – maximum width in pixels.
height – maximum height in pixels.
kwargs – optional arguments. Some options are encoding, jpegQuality, jpegSubsampling, and tiffCompression.
- Returns
thumbData, thumbMime: the image data and the mime type.
- getTile(x, y, z, pilImageAllowed=False, numpyAllowed=False, sparseFallback=False, frame=None)[source]¶
Get a tile from a tile source, returning it as an binary image, a PIL image, or a numpy array.
- Parameters
x – the 0-based x position of the tile on the specified z level. 0 is left.
y – the 0-based y position of the tile on the specified z level. 0 is top.
z – the z level of the tile. May range from [0, self.levels], where 0 is the lowest resolution, single tile for the whole source.
pilImageAllowed – True if a PIL image may be returned.
numpyAllowed – True if a numpy image may be returned. ‘always’ to return a numpy array.
sparseFallback – if False and a tile doesn’t exist, raise an error. If True, check if a lower resolution tile exists, and, if so, interpolate the needed data for this tile.
frame – the frame number within the tile source. None is the same as 0 for multi-frame sources.
- Returns
either a numpy array, a PIL image, or a memory object with an image file.
- getTileCount(*args, **kwargs)[source]¶
Return the number of tiles that the tileIterator will return. See tileIterator for parameters.
- Returns
the number of tiles that the tileIterator will yield.
- getTileMimeType()[source]¶
Return the default mimetype for image tiles.
- Returns
the mime type of the tile.
- histogram(dtype=None, onlyMinMax=False, bins=256, density=False, format=None, *args, **kwargs)[source]¶
Get a histogram for a region.
- Parameters
dtype – if specified, the tiles must be this numpy.dtype.
onlyMinMax – if True, only return the minimum and maximum value of the region.
bins – the number of bins in the histogram. This is passed to numpy.histogram, but needs to produce the same set of edges for each tile.
density – if True, scale the results based on the number of samples.
format – ignored. Used to override the format for the tileIterator.
range – if None, use the computed min and (max + 1). Otherwise, this is the range passed to numpy.histogram. Note this is only accessible via kwargs as it otherwise overloads the range function.
args – parameters to pass to the tileIterator.
kwargs – parameters to pass to the tileIterator.
- Returns
if onlyMinMax is true, this is a dictionary with keys min and max, each of which is a numpy array with the minimum and maximum of all of the bands. If onlyMinMax is False, this is a dictionary with a single key ‘histogram’ that contains a list of histograms per band. Each entry is a dictionary with min, max, range, hist, and bin_edges. range is [min, (max + 1)]. hist is the counts (normalized if density is True) for each bin. bin_edges is an array one longer than the hist array that contains the boundaries between bins.
- mimeTypes = {None: 8}¶
A dictionary of common mime-types handled by the source and the
SourcePriority
given to each. This are used in place of or in additional to extensions.
- name = None¶
Name of the tile source
- tileFrames(format=('image',), frameList=None, framesAcross=None, **kwargs)[source]¶
Given the parameters for getRegion, plus a list of frames and the number of frames across, make a larger image composed of a region from each listed frame composited together.
- Parameters
format – the desired format or a tuple of allowed formats. Formats are members of (TILE_FORMAT_PIL, TILE_FORMAT_NUMPY, TILE_FORMAT_IMAGE). If TILE_FORMAT_IMAGE, encoding may be specified.
frameList – None for all frames, or a list of 0-based integers.
framesAcross – the number of frames across the final image. If unspecified, this is the ceiling of sqrt(number of frames in frame list).
kwargs – optional arguments. Some options are region, output, encoding, jpegQuality, jpegSubsampling, tiffCompression, fill. See tileIterator.
- Returns
regionData, formatOrRegionMime: the image data and either the mime type, if the format is TILE_FORMAT_IMAGE, or the format.
- tileIterator(format=('numpy',), resample=True, **kwargs)[source]¶
Iterate on all tiles in the specified region at the specified scale. Each tile is returned as part of a dictionary that includes
- x, y
(left, top) coordinates in current magnification pixels
- width, height
size of current tile in current magnification pixels
- tile
cropped tile image
- format
format of the tile
- level
level of the current tile
- level_x, level_y
the tile reference number within the level. Tiles are numbered (0, 0), (1, 0), (2, 0), etc. The 0th tile yielded may not be (0, 0) if a region is specified.
- tile_position
a dictionary of the tile position within the iterator, containing:
- level_x, level_y
the tile reference number within the level.
- region_x, region_y
0, 0 is the first tile in the full iteration (when not restricting the iteration to a single tile).
- position
a 0-based value for the tile within the full iteration.
- iterator_range
a dictionary of the output range of the iterator:
- level_x_min, level_x_max
the tiles that are be included during the full iteration: [layer_x_min, layer_x_max).
- level_y_min, level_y_max
the tiles that are be included during the full iteration: [layer_y_min, layer_y_max).
- region_x_max, region_y_max
the number of tiles included during the full iteration. This is layer_x_max - layer_x_min, layer_y_max - layer_y_min.
- position
the total number of tiles included in the full iteration. This is region_x_max * region_y_max.
- magnification
magnification of the current tile
- mm_x, mm_y
size of the current tile pixel in millimeters.
- gx, gy
(left, top) coordinates in maximum-resolution pixels
- gwidth, gheight
size of of the current tile in maximum-resolution pixels.
- tile_overlap
the amount of overlap with neighboring tiles (left, top, right, and bottom). Overlap never extends outside of the requested region.
If a region that includes partial tiles is requested, those tiles are cropped appropriately. Most images will have tiles that get cropped along the right and bottom edges in any case. If an exact magnification or scale is requested, no tiles will be returned.
- Parameters
format – the desired format or a tuple of allowed formats. Formats are members of (TILE_FORMAT_PIL, TILE_FORMAT_NUMPY, TILE_FORMAT_IMAGE). If TILE_FORMAT_IMAGE, encoding must be specified.
resample –
If True or one of PIL.Image.Resampling.NEAREST, LANCZOS, BILINEAR, or BICUBIC to resample tiles that are not the target output size. Tiles that are resampled will have additional dictionary entries of:
- scaled
the scaling factor that was applied (less than 1 is downsampled).
- tile_x, tile_y
(left, top) coordinates before scaling
- tile_width, tile_height
size of the current tile before scaling.
- tile_magnification
magnification of the current tile before scaling.
- tile_mm_x, tile_mm_y
size of a pixel in a tile in millimeters before scaling.
Note that scipy.misc.imresize uses PIL internally.
region –
a dictionary of optional values which specify the part of the image to process:
- left
the left edge (inclusive) of the region to process.
- top
the top edge (inclusive) of the region to process.
- right
the right edge (exclusive) of the region to process.
- bottom
the bottom edge (exclusive) of the region to process.
- width
the width of the region to process.
- height
the height of the region to process.
- units
either ‘base_pixels’ (default), ‘pixels’, ‘mm’, or ‘fraction’. base_pixels are in maximum resolution pixels. pixels is in the specified magnification pixels. mm is in the specified magnification scale. fraction is a scale of 0 to 1. pixels and mm are only available if the magnification and mm per pixel are defined for the image.
output –
a dictionary of optional values which specify the size of the output.
- maxWidth
maximum width in pixels. If either maxWidth or maxHeight is specified, magnification, mm_x, and mm_y are ignored.
- maxHeight
maximum height in pixels.
scale –
a dictionary of optional values which specify the scale of the region and / or output. This applies to region if pixels or mm are used for inits. It applies to output if neither output maxWidth nor maxHeight is specified.
- magnification
the magnification ratio. Only used is maxWidth and maxHeight are not specified or None.
- mm_x
the horizontal size of a pixel in millimeters.
- mm_y
the vertical size of a pixel in millimeters.
- exact
if True, only a level that matches exactly will be returned. This is only applied if magnification, mm_x, or mm_y is used.
tile_position – if present, either a number to only yield the (tile_position)th tile [0 to (xmax - min) * (ymax - ymin)) that the iterator would yield, or a dictionary of {region_x, region_y} to yield that tile, where 0, 0 is the first tile yielded, and xmax - xmin - 1, ymax - ymin - 1 is the last tile yielded, or a dictionary of {level_x, level_y} to yield that specific tile if it is in the region.
tile_size –
if present, retile the output to the specified tile size. If only width or only height is specified, the resultant tiles will be square. This is a dictionary containing at least one of:
- width
the desired tile width.
- height
the desired tile height.
tile_overlap –
if present, retile the output adding a symmetric overlap to the tiles. If either x or y is not specified, it defaults to zero. The overlap does not change the tile size, only the stride of the tiles. This is a dictionary containing:
- x
the horizontal overlap in pixels.
- y
the vertical overlap in pixels.
- edges
if True, then the edge tiles will exclude the overlap distance. If unset or False, the edge tiles are full size.
The overlap is conceptually split between the two sides of the tile. This is only relevant to where overlap is reported or if edges is True
As an example, suppose an image that is 8 pixels across (01234567) and a tile size of 5 is requested with an overlap of 4. If the edges option is False (the default), the following tiles are returned: 01234, 12345, 23456, 34567. Each tile reports its overlap, and the non-overlapped area of each tile is 012, 3, 4, 567. If the edges option is True, the tiles returned are: 012, 0123, 01234, 12345, 23456, 34567, 4567, 567, with the non-overlapped area of each as 0, 1, 2, 3, 4, 5, 6, 7.
encoding – if format includes TILE_FORMAT_IMAGE, a valid PIL encoding (typically ‘PNG’, ‘JPEG’, or ‘TIFF’) or ‘TILED’ (identical to TIFF). Must also be in the TileOutputMimeTypes map.
jpegQuality – the quality to use when encoding a JPEG.
jpegSubsampling – the subsampling level to use when encoding a JPEG.
tiffCompression – the compression format when encoding a TIFF. This is usually ‘raw’, ‘tiff_lzw’, ‘jpeg’, or ‘tiff_adobe_deflate’. Some of these are aliased: ‘none’, ‘lzw’, ‘deflate’.
frame – the frame number within the tile source. None is the same as 0 for multi-frame sources.
kwargs – optional arguments.
- Yields
an iterator that returns a dictionary as listed above.
- tileIteratorAtAnotherScale(sourceRegion, sourceScale=None, targetScale=None, targetUnits=None, **kwargs)[source]¶
This takes the same parameters and returns the same results as tileIterator, except instead of region and scale, it takes sourceRegion, sourceScale, targetScale, and targetUnits. These parameters are the same as convertRegionScale. See those two functions for parameter definitions.
- exception large_image.tilesource.TileSourceAssetstoreError[source]¶
Bases:
TileSourceError
- large_image.tilesource.TileSourceAssetstoreException¶
alias of
TileSourceAssetstoreError
- exception large_image.tilesource.TileSourceError[source]¶
Bases:
TileGeneralError
- large_image.tilesource.TileSourceException¶
alias of
TileSourceError
- exception large_image.tilesource.TileSourceFileNotFoundError(*args, **kwargs)[source]¶
Bases:
TileSourceError
,FileNotFoundError
- large_image.tilesource.canRead(*args, **kwargs)[source]¶
Check if large_image can read a path or uri.
- Returns
True if any appropriate source reports it can read the path or uri.
- large_image.tilesource.dictToEtree(d, root=None)[source]¶
Convert a dictionary in the style produced by etreeToDict back to an etree. Make an xml string via xml.etree.ElementTree.tostring(dictToEtree( dictionary), encoding=’utf8’, method=’xml’). Note that this function and etreeToDict are not perfect conversions; numerical values are quoted in xml. Plain key-value pairs are ambiguous whether they should be attributes or text values. Text fields are collected together.
- Parameters
d – a dictionary.
- Prarm root
the root node to attach this dictionary to.
- Returns
an etree.
- large_image.tilesource.etreeToDict(t)[source]¶
Convert an xml etree to a nested dictionary without schema names in the keys. If you have an xml string, this can be converted to a dictionary via xml.etree.etreeToDict(ElementTree.fromstring(xml_string)).
- Parameters
t – an etree.
- Returns
a python dictionary with the results.
- large_image.tilesource.getSourceNameFromDict(availableSources, pathOrUri, *args, **kwargs)[source]¶
Get a tile source based on a ordered dictionary of known sources and a path name or URI. Additional parameters are passed to the tile source and can be used for properties such as encoding.
- Parameters
availableSources – an ordered dictionary of sources to try.
pathOrUri – either a file path or a fixed source via large_image://<source>.
- Returns
the name of a tile source that can read the input, or None if there is no such source.
- large_image.tilesource.getTileSource(*args, **kwargs)[source]¶
Get a tilesource using the known sources. If tile sources have not yet been loaded, load them.
- Returns
A tilesource for the passed arguments.
- large_image.tilesource.nearPowerOfTwo(val1, val2, tolerance=0.02)[source]¶
Check if two values are different by nearly a power of two.
- Parameters
val1 – the first value to check.
val2 – the second value to check.
tolerance – the maximum difference in the log2 ratio’s mantissa.
- Returns
True if the valeus are nearly a power of two different from each other; false otherwise.