ImageMorph.py 7.8 KB

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