ImageMorph.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. msg = "Unknown pattern " + op_name + "!"
  67. raise Exception(msg)
  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[: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[: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. msg = 'Syntax error in pattern "' + p + '"'
  120. raise Exception(msg)
  121. options = m.group(1)
  122. pattern = m.group(2)
  123. result = int(m.group(3))
  124. # Get rid of spaces
  125. pattern = pattern.replace(" ", "").replace("\n", "")
  126. patterns += self._pattern_permute(pattern, options, result)
  127. # compile the patterns into regular expressions for speed
  128. for i, pattern in enumerate(patterns):
  129. p = pattern[0].replace(".", "X").replace("X", "[01]")
  130. p = re.compile(p)
  131. patterns[i] = (p, pattern[1])
  132. # Step through table and find patterns that match.
  133. # Note that all the patterns are searched. The last one
  134. # caught overrides
  135. for i in range(LUT_SIZE):
  136. # Build the bit pattern
  137. bitpattern = bin(i)[2:]
  138. bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
  139. for p, r in patterns:
  140. if p.match(bitpattern):
  141. self.lut[i] = [0, 1][r]
  142. return self.lut
  143. class MorphOp:
  144. """A class for binary morphological operators"""
  145. def __init__(self, lut=None, op_name=None, patterns=None):
  146. """Create a binary morphological operator"""
  147. self.lut = lut
  148. if op_name is not None:
  149. self.lut = LutBuilder(op_name=op_name).build_lut()
  150. elif patterns is not None:
  151. self.lut = LutBuilder(patterns=patterns).build_lut()
  152. def apply(self, image):
  153. """Run a single morphological operation on an image
  154. Returns a tuple of the number of changed pixels and the
  155. morphed image"""
  156. if self.lut is None:
  157. msg = "No operator loaded"
  158. raise Exception(msg)
  159. if image.mode != "L":
  160. msg = "Image mode must be L"
  161. raise ValueError(msg)
  162. outimage = Image.new(image.mode, image.size, None)
  163. count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
  164. return count, outimage
  165. def match(self, image):
  166. """Get a list of coordinates matching the morphological operation on
  167. an image.
  168. Returns a list of tuples of (x,y) coordinates
  169. of all matching pixels. See :ref:`coordinate-system`."""
  170. if self.lut is None:
  171. msg = "No operator loaded"
  172. raise Exception(msg)
  173. if image.mode != "L":
  174. msg = "Image mode must be L"
  175. raise ValueError(msg)
  176. return _imagingmorph.match(bytes(self.lut), image.im.id)
  177. def get_on_pixels(self, image):
  178. """Get a list of all turned on pixels in a binary image
  179. Returns a list of tuples of (x,y) coordinates
  180. of all matching pixels. See :ref:`coordinate-system`."""
  181. if image.mode != "L":
  182. msg = "Image mode must be L"
  183. raise ValueError(msg)
  184. return _imagingmorph.get_on_pixels(image.im.id)
  185. def load_lut(self, filename):
  186. """Load an operator from an mrl file"""
  187. with open(filename, "rb") as f:
  188. self.lut = bytearray(f.read())
  189. if len(self.lut) != LUT_SIZE:
  190. self.lut = None
  191. msg = "Wrong size operator file!"
  192. raise Exception(msg)
  193. def save_lut(self, filename):
  194. """Save an operator to an mrl file"""
  195. if self.lut is None:
  196. msg = "No operator loaded"
  197. raise Exception(msg)
  198. with open(filename, "wb") as f:
  199. f.write(self.lut)
  200. def set_lut(self, lut):
  201. """Set the lut from an external source"""
  202. self.lut = lut