ImageMorph.py 7.7 KB

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