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