ImageMorph.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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__(self, patterns=None, op_name=None):
  48. if patterns is not None:
  49. self.patterns = patterns
  50. else:
  51. self.patterns = []
  52. self.lut = None
  53. if op_name is not None:
  54. known_patterns = {
  55. "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
  56. "dilation4": ["4:(... .0. .1.)->1"],
  57. "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
  58. "erosion4": ["4:(... .1. .0.)->0"],
  59. "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
  60. "edge": [
  61. "1:(... ... ...)->0",
  62. "4:(.0. .1. ...)->1",
  63. "4:(01. .1. ...)->1",
  64. ],
  65. }
  66. if op_name not in known_patterns:
  67. msg = "Unknown pattern " + op_name + "!"
  68. raise Exception(msg)
  69. self.patterns = known_patterns[op_name]
  70. def add_patterns(self, patterns):
  71. self.patterns += patterns
  72. def build_default_lut(self):
  73. symbols = [0, 1]
  74. m = 1 << 4 # pos of current pixel
  75. self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
  76. def get_lut(self):
  77. return self.lut
  78. def _string_permute(self, pattern, permutation):
  79. """string_permute takes a pattern and a permutation and returns the
  80. string permuted according to the permutation list.
  81. """
  82. assert len(permutation) == 9
  83. return "".join(pattern[p] for p in permutation)
  84. def _pattern_permute(self, basic_pattern, options, basic_result):
  85. """pattern_permute takes a basic pattern and its result and clones
  86. the pattern according to the modifications described in the $options
  87. parameter. It returns a list of all cloned patterns."""
  88. patterns = [(basic_pattern, basic_result)]
  89. # rotations
  90. if "4" in options:
  91. res = patterns[-1][1]
  92. for i in range(4):
  93. patterns.append(
  94. (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
  95. )
  96. # mirror
  97. if "M" in options:
  98. n = len(patterns)
  99. for pattern, res in patterns[:n]:
  100. patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
  101. # negate
  102. if "N" in options:
  103. n = len(patterns)
  104. for pattern, res in patterns[:n]:
  105. # Swap 0 and 1
  106. pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
  107. res = 1 - int(res)
  108. patterns.append((pattern, res))
  109. return patterns
  110. def build_lut(self):
  111. """Compile all patterns into a morphology lut.
  112. TBD :Build based on (file) morphlut:modify_lut
  113. """
  114. self.build_default_lut()
  115. patterns = []
  116. # Parse and create symmetries of the patterns strings
  117. for p in self.patterns:
  118. m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
  119. if not m:
  120. msg = 'Syntax error in pattern "' + p + '"'
  121. raise Exception(msg)
  122. options = m.group(1)
  123. pattern = m.group(2)
  124. result = int(m.group(3))
  125. # Get rid of spaces
  126. pattern = pattern.replace(" ", "").replace("\n", "")
  127. patterns += self._pattern_permute(pattern, options, result)
  128. # compile the patterns into regular expressions for speed
  129. for i, pattern in enumerate(patterns):
  130. p = pattern[0].replace(".", "X").replace("X", "[01]")
  131. p = re.compile(p)
  132. patterns[i] = (p, pattern[1])
  133. # Step through table and find patterns that match.
  134. # Note that all the patterns are searched. The last one
  135. # caught overrides
  136. for i in range(LUT_SIZE):
  137. # Build the bit pattern
  138. bitpattern = bin(i)[2:]
  139. bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
  140. for p, r in patterns:
  141. if p.match(bitpattern):
  142. self.lut[i] = [0, 1][r]
  143. return self.lut
  144. class MorphOp:
  145. """A class for binary morphological operators"""
  146. def __init__(self, lut=None, op_name=None, patterns=None):
  147. """Create a binary morphological operator"""
  148. self.lut = lut
  149. if op_name is not None:
  150. self.lut = LutBuilder(op_name=op_name).build_lut()
  151. elif patterns is not None:
  152. self.lut = LutBuilder(patterns=patterns).build_lut()
  153. def apply(self, image):
  154. """Run a single morphological operation on an image
  155. Returns a tuple of the number of changed pixels and the
  156. morphed image"""
  157. if self.lut is None:
  158. msg = "No operator loaded"
  159. raise Exception(msg)
  160. if image.mode != "L":
  161. msg = "Image mode must be L"
  162. raise ValueError(msg)
  163. outimage = Image.new(image.mode, image.size, None)
  164. count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
  165. return count, outimage
  166. def match(self, image):
  167. """Get a list of coordinates matching the morphological operation on
  168. an image.
  169. Returns a list of tuples of (x,y) coordinates
  170. of all matching pixels. See :ref:`coordinate-system`."""
  171. if self.lut is None:
  172. msg = "No operator loaded"
  173. raise Exception(msg)
  174. if image.mode != "L":
  175. msg = "Image mode must be L"
  176. raise ValueError(msg)
  177. return _imagingmorph.match(bytes(self.lut), image.im.id)
  178. def get_on_pixels(self, image):
  179. """Get a list of all turned on pixels in a binary image
  180. Returns a list of tuples of (x,y) coordinates
  181. of all matching pixels. See :ref:`coordinate-system`."""
  182. if image.mode != "L":
  183. msg = "Image mode must be L"
  184. raise ValueError(msg)
  185. return _imagingmorph.get_on_pixels(image.im.id)
  186. def load_lut(self, filename):
  187. """Load an operator from an mrl file"""
  188. with open(filename, "rb") as f:
  189. self.lut = bytearray(f.read())
  190. if len(self.lut) != LUT_SIZE:
  191. self.lut = None
  192. msg = "Wrong size operator file!"
  193. raise Exception(msg)
  194. def save_lut(self, filename):
  195. """Save an operator to an mrl file"""
  196. if self.lut is None:
  197. msg = "No operator loaded"
  198. raise Exception(msg)
  199. with open(filename, "wb") as f:
  200. f.write(self.lut)
  201. def set_lut(self, lut):
  202. """Set the lut from an external source"""
  203. self.lut = lut