Added type hints

This commit is contained in:
Andrew Murray 2024-01-11 23:11:12 +11:00
parent d6d6c7c989
commit bc192557b8
3 changed files with 35 additions and 21 deletions

View File

@ -146,7 +146,6 @@ exclude = [
'^src/PIL/DdsImagePlugin.py$', '^src/PIL/DdsImagePlugin.py$',
'^src/PIL/FpxImagePlugin.py$', '^src/PIL/FpxImagePlugin.py$',
'^src/PIL/Image.py$', '^src/PIL/Image.py$',
'^src/PIL/ImageMorph.py$',
'^src/PIL/ImageQt.py$', '^src/PIL/ImageQt.py$',
'^src/PIL/ImageShow.py$', '^src/PIL/ImageShow.py$',
'^src/PIL/ImImagePlugin.py$', '^src/PIL/ImImagePlugin.py$',

View File

@ -62,12 +62,14 @@ class LutBuilder:
""" """
def __init__(self, patterns=None, op_name=None): def __init__(
self, patterns: list[str] | None = None, op_name: str | None = None
) -> None:
if patterns is not None: if patterns is not None:
self.patterns = patterns self.patterns = patterns
else: else:
self.patterns = [] self.patterns = []
self.lut = None self.lut: bytearray | None = None
if op_name is not None: if op_name is not None:
known_patterns = { known_patterns = {
"corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"], "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
@ -87,25 +89,27 @@ class LutBuilder:
self.patterns = known_patterns[op_name] self.patterns = known_patterns[op_name]
def add_patterns(self, patterns): def add_patterns(self, patterns: list[str]) -> None:
self.patterns += patterns self.patterns += patterns
def build_default_lut(self): def build_default_lut(self) -> None:
symbols = [0, 1] symbols = [0, 1]
m = 1 << 4 # pos of current pixel m = 1 << 4 # pos of current pixel
self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE)) self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
def get_lut(self): def get_lut(self) -> bytearray | None:
return self.lut return self.lut
def _string_permute(self, pattern, permutation): def _string_permute(self, pattern: str, permutation: list[int]) -> str:
"""string_permute takes a pattern and a permutation and returns the """string_permute takes a pattern and a permutation and returns the
string permuted according to the permutation list. string permuted according to the permutation list.
""" """
assert len(permutation) == 9 assert len(permutation) == 9
return "".join(pattern[p] for p in permutation) return "".join(pattern[p] for p in permutation)
def _pattern_permute(self, basic_pattern, options, basic_result): def _pattern_permute(
self, basic_pattern: str, options: str, basic_result: int
) -> list[tuple[str, int]]:
"""pattern_permute takes a basic pattern and its result and clones """pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns.""" parameter. It returns a list of all cloned patterns."""
@ -135,12 +139,13 @@ class LutBuilder:
return patterns return patterns
def build_lut(self): def build_lut(self) -> bytearray:
"""Compile all patterns into a morphology lut. """Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut TBD :Build based on (file) morphlut:modify_lut
""" """
self.build_default_lut() self.build_default_lut()
assert self.lut is not None
patterns = [] patterns = []
# Parse and create symmetries of the patterns strings # Parse and create symmetries of the patterns strings
@ -159,10 +164,10 @@ class LutBuilder:
patterns += self._pattern_permute(pattern, options, result) patterns += self._pattern_permute(pattern, options, result)
# compile the patterns into regular expressions for speed # compile the patterns into regular expressions for speed
for i, pattern in enumerate(patterns): compiled_patterns = []
for pattern in patterns:
p = pattern[0].replace(".", "X").replace("X", "[01]") p = pattern[0].replace(".", "X").replace("X", "[01]")
p = re.compile(p) compiled_patterns.append((re.compile(p), pattern[1]))
patterns[i] = (p, pattern[1])
# Step through table and find patterns that match. # Step through table and find patterns that match.
# Note that all the patterns are searched. The last one # Note that all the patterns are searched. The last one
@ -172,8 +177,8 @@ class LutBuilder:
bitpattern = bin(i)[2:] bitpattern = bin(i)[2:]
bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1] bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
for p, r in patterns: for pattern, r in compiled_patterns:
if p.match(bitpattern): if pattern.match(bitpattern):
self.lut[i] = [0, 1][r] self.lut[i] = [0, 1][r]
return self.lut return self.lut
@ -182,7 +187,12 @@ class LutBuilder:
class MorphOp: class MorphOp:
"""A class for binary morphological operators""" """A class for binary morphological operators"""
def __init__(self, lut=None, op_name=None, patterns=None): def __init__(
self,
lut: bytearray | None = None,
op_name: str | None = None,
patterns: list[str] | None = None,
) -> None:
"""Create a binary morphological operator""" """Create a binary morphological operator"""
self.lut = lut self.lut = lut
if op_name is not None: if op_name is not None:
@ -190,7 +200,7 @@ class MorphOp:
elif patterns is not None: elif patterns is not None:
self.lut = LutBuilder(patterns=patterns).build_lut() self.lut = LutBuilder(patterns=patterns).build_lut()
def apply(self, image): def apply(self, image: Image.Image):
"""Run a single morphological operation on an image """Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the Returns a tuple of the number of changed pixels and the
@ -206,7 +216,7 @@ class MorphOp:
count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id) count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
return count, outimage return count, outimage
def match(self, image): def match(self, image: Image.Image):
"""Get a list of coordinates matching the morphological operation on """Get a list of coordinates matching the morphological operation on
an image. an image.
@ -221,7 +231,7 @@ class MorphOp:
raise ValueError(msg) raise ValueError(msg)
return _imagingmorph.match(bytes(self.lut), image.im.id) return _imagingmorph.match(bytes(self.lut), image.im.id)
def get_on_pixels(self, image): def get_on_pixels(self, image: Image.Image):
"""Get a list of all turned on pixels in a binary image """Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates Returns a list of tuples of (x,y) coordinates
@ -232,7 +242,7 @@ class MorphOp:
raise ValueError(msg) raise ValueError(msg)
return _imagingmorph.get_on_pixels(image.im.id) return _imagingmorph.get_on_pixels(image.im.id)
def load_lut(self, filename): def load_lut(self, filename: str) -> None:
"""Load an operator from an mrl file""" """Load an operator from an mrl file"""
with open(filename, "rb") as f: with open(filename, "rb") as f:
self.lut = bytearray(f.read()) self.lut = bytearray(f.read())
@ -242,7 +252,7 @@ class MorphOp:
msg = "Wrong size operator file!" msg = "Wrong size operator file!"
raise Exception(msg) raise Exception(msg)
def save_lut(self, filename): def save_lut(self, filename: str) -> None:
"""Save an operator to an mrl file""" """Save an operator to an mrl file"""
if self.lut is None: if self.lut is None:
msg = "No operator loaded" msg = "No operator loaded"
@ -250,6 +260,6 @@ class MorphOp:
with open(filename, "wb") as f: with open(filename, "wb") as f:
f.write(self.lut) f.write(self.lut)
def set_lut(self, lut): def set_lut(self, lut: bytearray | None) -> None:
"""Set the lut from an external source""" """Set the lut from an external source"""
self.lut = lut self.lut = lut

View File

@ -0,0 +1,5 @@
from __future__ import annotations
from typing import Any
def __getattr__(name: str) -> Any: ...