Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more type annotations #1438

Merged
merged 1 commit into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
- Optimizing when reading arrays rather than images from tiff files ([#1423](../../pull/1423))
- Better filter DICOM adjacent files to ensure they share series instance IDs ([#1424](../../pull/1424), [#1436](../../pull/1436))
- Optimizing small getRegion calls and some tiff tile fetches ([#1427](../../pull/1427))
- Started adding python types to the core library ([#1432](../../pull/1432), [#1433](../../pull/1433), [#1437](../../pull/1437))
- Started adding python types to the core library ([#1432](../../pull/1432), [#1433](../../pull/1433), [#1437](../../pull/1437), [#1438](../../pull/1438))
- Use parallelism in computing tile frames ([#1434](../../pull/1434))

### Changed
Expand Down
37 changes: 20 additions & 17 deletions large_image/tilesource/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -842,8 +842,9 @@ def _tileIterator(self, iterInfo: Dict[str, Any]) -> Iterator[LazyTileDict]:

self.logger.debug(
'Fetching region of an image with a source size of %d x %d; '
'getting %d tiles',
regionWidth, regionHeight, (xmax - xmin) * (ymax - ymin))
'getting %d tile%s',
regionWidth, regionHeight, (xmax - xmin) * (ymax - ymin),
'' if (xmax - xmin) * (ymax - ymin) == 1 else 's')

# If tile is specified, return at most one tile
if iterInfo.get('tile_position') is not None:
Expand Down Expand Up @@ -1604,7 +1605,7 @@ def _outputTileNumpyStyle(
tile = self._applyStyle(tile, getattr(self, 'style', None), x, y, z, frame)
if tile.shape[0] != self.tileHeight or tile.shape[1] != self.tileWidth:
extend = np.zeros(
(self.tileHeight, self.tileWidth, tile.shape[2]),
(self.tileHeight, self.tileWidth, tile.shape[2]), # type: ignore[misc]
dtype=tile.dtype)
extend[:min(self.tileHeight, tile.shape[0]),
:min(self.tileWidth, tile.shape[1])] = tile
Expand Down Expand Up @@ -1672,10 +1673,10 @@ def _outputTile(
sizeY - (maxY - self.tileHeight))
tile, mode = _imageToNumpy(tile)
if self.edge in (True, 'crop'):
tile = cast(np.ndarray, tile)[:contentHeight, :contentWidth]
tile = tile[:contentHeight, :contentWidth]
else:
color = PIL.ImageColor.getcolor(self.edge, cast(str, mode))
tile = cast(np.ndarray, tile).copy()
color = PIL.ImageColor.getcolor(self.edge, mode)
tile = tile.copy()
tile[:, contentWidth:] = color
tile[contentHeight:] = color
if isinstance(tile, np.ndarray) and numpyAllowed:
Expand Down Expand Up @@ -2207,7 +2208,7 @@ def getRegion(self, format: Union[str, Tuple[str]] = (TILE_FORMAT_IMAGE, ), **kw
mode = None if TILE_FORMAT_NUMPY in format else iterInfo['mode']
outWidth = iterInfo['output']['width']
outHeight = iterInfo['output']['height']
image: Optional[np.ndarray] = None
image: Optional[Union[np.ndarray, PIL.Image.Image, ImageBytes, bytes]] = None
tiledimage = None
for tile in self._tileIterator(iterInfo):
# Add each tile to the image
Expand All @@ -2218,7 +2219,7 @@ def getRegion(self, format: Union[str, Tuple[str]] = (TILE_FORMAT_IMAGE, ), **kw
tiledimage, subimage, x0, y0, regionWidth, regionHeight, tile, **kwargs)
else:
image = utilities._addSubimageToImage(
image, subimage, x0, y0, regionWidth, regionHeight)
cast(Optional[np.ndarray], image), subimage, x0, y0, regionWidth, regionHeight)
# Somehow discarding the tile here speeds things up.
del tile
del subimage
Expand All @@ -2230,7 +2231,7 @@ def getRegion(self, format: Union[str, Tuple[str]] = (TILE_FORMAT_IMAGE, ), **kw
cast(Dict[str, Any], tiledimage), outWidth, outHeight, iterInfo, **kwargs)
if outWidth != regionWidth or outHeight != regionHeight:
dtype = cast(np.ndarray, image).dtype
image = _imageToPIL(image, mode).resize(
image = _imageToPIL(cast(np.ndarray, image), mode).resize(
(outWidth, outHeight),
getattr(PIL.Image, 'Resampling', PIL.Image).BICUBIC
if outWidth > regionWidth else
Expand All @@ -2241,8 +2242,8 @@ def getRegion(self, format: Union[str, Tuple[str]] = (TILE_FORMAT_IMAGE, ), **kw
maxHeight = kwargs.get('output', {}).get('maxHeight')
if kwargs.get('fill') and maxWidth and maxHeight:
image = utilities._letterboxImage(
_imageToPIL(image, mode), maxWidth, maxHeight, kwargs['fill'])
return utilities._encodeImage(image, format=format, **kwargs)
_imageToPIL(cast(np.ndarray, image), mode), maxWidth, maxHeight, kwargs['fill'])
return utilities._encodeImage(cast(np.ndarray, image), format=format, **kwargs)

def _encodeTiledImage(
self, image: Dict[str, Any], outWidth: int, outHeight: int,
Expand Down Expand Up @@ -2435,14 +2436,16 @@ def tileFrames(
frame, idx, len(frameList), offsetX, offsetY)
if tiled:
tiledimage = utilities._addRegionTileToTiled(
tiledimage, subimage, offsetX, offsetY, outWidth, outHeight, tile, **kwargs)
else:
image = utilities._addSubimageToImage(
image, subimage, offsetX, offsetY, outWidth, outHeight)
tiledimage, cast(np.ndarray, subimage), offsetX,
offsetY, outWidth, outHeight, tile, **kwargs)
else:
image = utilities._addSubimageToImage(
image, cast(np.ndarray, subimage), offsetX, offsetY,
outWidth, outHeight)
if tiled:
return self._encodeTiledImage(
cast(Dict[str, Any], tiledimage), outWidth, outHeight, iterInfo, **kwargs)
return utilities._encodeImage(image, format=format, **kwargs)
return utilities._encodeImage(cast(np.ndarray, image), format=format, **kwargs)

def getRegionAtAnotherScale(
self, sourceRegion: Dict[str, Any],
Expand Down Expand Up @@ -2851,7 +2854,7 @@ def getAssociatedImage(
getattr(PIL.Image, 'Resampling', PIL.Image).BICUBIC
if width > imageWidth else
getattr(PIL.Image, 'Resampling', PIL.Image).LANCZOS)
return utilities._encodeImage(image, **kwargs)
return cast(Tuple[ImageBytes, str], utilities._encodeImage(image, **kwargs))

def getPixel(self, includeTileRecord: bool = False, **kwargs) -> JSONDict:
"""
Expand Down
39 changes: 25 additions & 14 deletions large_image/tilesource/stylefuncs.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
# This module contains functions for use in styles

from types import SimpleNamespace
from typing import List, Optional, Tuple, Union

import numpy as np

from .utilities import _imageToNumpy, _imageToPIL


def maskPixelValues(image, context, values=None, negative=None, positive=None):
def maskPixelValues(
image: np.ndarray, context: SimpleNamespace,
values: List[Union[int, List[int], Tuple[int, ...]]],
negative: Optional[int] = None, positive: Optional[int] = None) -> np.ndarray:
"""
This is a style utility function that returns a black-and-white 8-bit image
where the image is white if the pixel of the source image is in a list of
Expand All @@ -27,21 +33,26 @@ def maskPixelValues(image, context, values=None, negative=None, positive=None):
src = context.image
mask = np.full(src.shape[:2], False)
for val in values:
vallist: List[float]
if not isinstance(val, (list, tuple)):
if src.shape[-1] == 1:
val = [val]
vallist = [val]
else:
val = [val % 256, val // 256 % 256, val // 65536 % 256]
val = (list(val) + [255] * src.shape[2])[:src.shape[2]]
match = np.array(val)
vallist = [val % 256, val // 256 % 256, val // 65536 % 256]
else:
vallist = list(val)
vallist = (vallist + [255] * src.shape[2])[:src.shape[2]]
match = np.array(vallist)
mask = mask | (src == match).all(axis=-1)
image[mask != True] = negative or [0, 0, 0, 255] # noqa E712
image[mask] = positive or [255, 255, 255, 0]
image = image.astype(np.uint8)
return image


def medianFilter(image, context=None, kernel=5, weight=1.0):
def medianFilter(
image: np.ndarray, context: Optional[SimpleNamespace] = None,
kernel: int = 5, weight: float = 1.0) -> np.ndarray:
"""
This is a style utility function that applies a median rank filter to the
image to sharpen it.
Expand All @@ -57,13 +68,13 @@ def medianFilter(image, context=None, kernel=5, weight=1.0):

filt = PIL.ImageFilter.MedianFilter(kernel)
if len(image.shape) != 3:
pimg = _imageToPIL(image)
pilimg = _imageToPIL(image)
elif image.shape[2] >= 3:
pimg = _imageToPIL(image[:, :, :3])
pilimg = _imageToPIL(image[:, :, :3])
else:
pimg = _imageToPIL(image[:, :, :1])
fimg = _imageToNumpy(pimg.filter(filt))[0]
mul = 0
pilimg = _imageToPIL(image[:, :, :1])
fimg = _imageToNumpy(pilimg.filter(filt))[0]
mul: float = 0
clip = 0
if image.dtype == np.uint8 or (
image.dtype.kind == 'f' and 1 < np.max(image) < 256 and np.min(image) >= 0):
Expand All @@ -79,12 +90,12 @@ def medianFilter(image, context=None, kernel=5, weight=1.0):
elif image.dtype.kind == 'f':
mul = 1
if mul:
pimg = image.astype(float)
pimg: np.ndarray = image.astype(float)
if len(pimg.shape) == 2:
pimg = np.resize(pimg, (pimg.shape[0], pimg.shape[1], 1))
pimg = pimg[:, :, :fimg.shape[2]]
pimg = pimg[:, :, :fimg.shape[2]] # type: ignore[index,misc]
dimg = (pimg - fimg.astype(float) * mul) * weight
pimg = pimg[:, :, :fimg.shape[2]] + dimg
pimg = pimg[:, :, :fimg.shape[2]] + dimg # type: ignore[index,misc]
if clip:
pimg = pimg.clip(0, clip)
if len(image.shape) != 3:
Expand Down
Loading