ImageMorph.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # A binary morphology add-on for the Python Imaging Library
  2. #
  3. # History:
  4. # 2014-06-04 Initial version.
  5. #
  6. # Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>
  7. from __future__ import annotations
  8. import re
  9. from . import Image, _imagingmorph
  10. LUT_SIZE = 1 << 9
  11. # fmt: off
  12. ROTATION_MATRIX = [
  13. 6, 3, 0,
  14. 7, 4, 1,
  15. 8, 5, 2,
  16. ]
  17. MIRROR_MATRIX = [
  18. 2, 1, 0,
  19. 5, 4, 3,
  20. 8, 7, 6,
  21. ]
  22. # fmt: on
  23. class LutBuilder:
  24. """A class for building a MorphLut from a descriptive language
  25. The input patterns is a list of a strings sequences like these::
  26. 4:(...
  27. .1.
  28. 111)->1
  29. (whitespaces including linebreaks are ignored). The option 4
  30. describes a series of symmetry operations (in this case a
  31. 4-rotation), the pattern is described by:
  32. - . or X - Ignore
  33. - 1 - Pixel is on
  34. - 0 - Pixel is off
  35. The result of the operation is described after "->" string.
  36. The default is to return the current pixel value, which is
  37. returned if no other match is found.
  38. Operations:
  39. - 4 - 4 way rotation
  40. - N - Negate
  41. - 1 - Dummy op for no other operation (an op must always be given)
  42. - M - Mirroring
  43. Example::
  44. lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
  45. lut = lb.build_lut()
  46. """
  47. def __init__(
  48. self, patterns: list[str] | None = None, op_name: str | None = None
  49. ) -> None:
  50. if patterns is not None:
  51. self.patterns = patterns
  52. else:
  53. self.patterns = []
  54. self.lut: bytearray | None = None
  55. if op_name is not None:
  56. known_patterns = {
  57. "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
  58. "dilation4": ["4:(... .0. .1.)->1"],
  59. "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
  60. "erosion4": ["4:(... .1. .0.)->0"],
  61. "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
  62. "edge": [
  63. "1:(... ... ...)->0",
  64. "4:(.0. .1. ...)->1",
  65. "4:(01. .1. ...)->1",
  66. ],
  67. }
  68. if op_name not in known_patterns:
  69. msg = f"Unknown pattern {op_name}!"
  70. raise Exception(msg)
  71. self.patterns = known_patterns[op_name]
  72. def add_patterns(self, patterns: list[str]) -> None:
  73. self.patterns += patterns
  74. def build_default_lut(self) -> None:
  75. symbols = [0, 1]
  76. m = 1 << 4 # pos of current pixel
  77. self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
  78. def get_lut(self) -> bytearray | None:
  79. return self.lut
  80. def _string_permute(self, pattern: str, permutation: list[int]) -> str:
  81. """string_permute takes a pattern and a permutation and returns the
  82. string permuted according to the permutation list.
  83. """
  84. assert len(permutation) == 9
  85. return "".join(pattern[p] for p in permutation)
  86. def _pattern_permute(
  87. self, basic_pattern: str, options: str, basic_result: int
  88. ) -> list[tuple[str, int]]:
  89. """pattern_permute takes a basic pattern and its result and clones
  90. the pattern according to the modifications described in the $options
  91. parameter. It returns a list of all cloned patterns."""
  92. patterns = [(basic_pattern, basic_result)]
  93. # rotations
  94. if "4" in options:
  95. res = patterns[-1][1]
  96. for i in range(4):
  97. patterns.append(
  98. (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
  99. )
  100. # mirror
  101. if "M" in options:
  102. n = len(patterns)
  103. for pattern, res in patterns[:n]:
  104. patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
  105. # negate
  106. if "N" in options:
  107. n = len(patterns)
  108. for pattern, res in patterns[:n]:
  109. # Swap 0 and 1
  110. pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
  111. res = 1 - int(res)
  112. patterns.append((pattern, res))
  113. return patterns
  114. def build_lut(self) -> bytearray:
  115. """Compile all patterns into a morphology lut.
  116. TBD :Build based on (file) morphlut:modify_lut
  117. """
  118. self.build_default_lut()
  119. assert self.lut is not None
  120. patterns = []
  121. # Parse and create symmetries of the patterns strings
  122. for p in self.patterns:
  123. m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
  124. if not m:
  125. msg = 'Syntax error in pattern "' + p + '"'
  126. raise Exception(msg)
  127. options = m.group(1)
  128. pattern = m.group(2)
  129. result = int(m.group(3))
  130. # Get rid of spaces
  131. pattern = pattern.replace(" ", "").replace("\n", "")
  132. patterns += self._pattern_permute(pattern, options, result)
  133. # compile the patterns into regular expressions for speed
  134. compiled_patterns = []
  135. for pattern in patterns:
  136. p = pattern[0].replace(".", "X").replace("X", "[01]")
  137. compiled_patterns.append((re.compile(p), pattern[1]))
  138. # Step through table and find patterns that match.
  139. # Note that all the patterns are searched. The last one
  140. # caught overrides
  141. for i in range(LUT_SIZE):
  142. # Build the bit pattern
  143. bitpattern = bin(i)[2:]
  144. bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
  145. for pattern, r in compiled_patterns:
  146. if pattern.match(bitpattern):
  147. self.lut[i] = [0, 1][r]
  148. return self.lut
  149. class MorphOp:
  150. """A class for binary morphological operators"""
  151. def __init__(
  152. self,
  153. lut: bytearray | None = None,
  154. op_name: str | None = None,
  155. patterns: list[str] | None = None,
  156. ) -> None:
  157. """Create a binary morphological operator"""
  158. self.lut = lut
  159. if op_name is not None:
  160. self.lut = LutBuilder(op_name=op_name).build_lut()
  161. elif patterns is not None:
  162. self.lut = LutBuilder(patterns=patterns).build_lut()
  163. def apply(self, image: Image.Image) -> tuple[int, Image.Image]:
  164. """Run a single morphological operation on an image
  165. Returns a tuple of the number of changed pixels and the
  166. morphed image"""
  167. if self.lut is None:
  168. msg = "No operator loaded"
  169. raise Exception(msg)
  170. if image.mode != "L":
  171. msg = "Image mode must be L"
  172. raise ValueError(msg)
  173. outimage = Image.new(image.mode, image.size, None)
  174. count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim())
  175. return count, outimage
  176. def match(self, image: Image.Image) -> list[tuple[int, int]]:
  177. """Get a list of coordinates matching the morphological operation on
  178. an image.
  179. Returns a list of tuples of (x,y) coordinates
  180. of all matching pixels. See :ref:`coordinate-system`."""
  181. if self.lut is None:
  182. msg = "No operator loaded"
  183. raise Exception(msg)
  184. if image.mode != "L":
  185. msg = "Image mode must be L"
  186. raise ValueError(msg)
  187. return _imagingmorph.match(bytes(self.lut), image.getim())
  188. def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:
  189. """Get a list of all turned on pixels in a binary image
  190. Returns a list of tuples of (x,y) coordinates
  191. of all matching pixels. See :ref:`coordinate-system`."""
  192. if image.mode != "L":
  193. msg = "Image mode must be L"
  194. raise ValueError(msg)
  195. return _imagingmorph.get_on_pixels(image.getim())
  196. def load_lut(self, filename: str) -> None:
  197. """Load an operator from an mrl file"""
  198. with open(filename, "rb") as f:
  199. self.lut = bytearray(f.read())
  200. if len(self.lut) != LUT_SIZE:
  201. self.lut = None
  202. msg = "Wrong size operator file!"
  203. raise Exception(msg)
  204. def save_lut(self, filename: str) -> None:
  205. """Save an operator to an mrl file"""
  206. if self.lut is None:
  207. msg = "No operator loaded"
  208. raise Exception(msg)
  209. with open(filename, "wb") as f:
  210. f.write(self.lut)
  211. def set_lut(self, lut: bytearray | None) -> None:
  212. """Set the lut from an external source"""
  213. self.lut = lut