ImageMorph.py 10 KB

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