ImageMath.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # a simple math add-on for the Python Imaging Library
  6. #
  7. # History:
  8. # 1999-02-15 fl Original PIL Plus release
  9. # 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6
  10. # 2005-09-12 fl Fixed int() and float() for Python 2.4.1
  11. #
  12. # Copyright (c) 1999-2005 by Secret Labs AB
  13. # Copyright (c) 2005 by Fredrik Lundh
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. import builtins
  18. from . import Image, _imagingmath
  19. VERBOSE = 0
  20. def _isconstant(v):
  21. return isinstance(v, (int, float))
  22. class _Operand:
  23. """Wraps an image operand, providing standard operators"""
  24. def __init__(self, im):
  25. self.im = im
  26. def __fixup(self, im1):
  27. # convert image to suitable mode
  28. if isinstance(im1, _Operand):
  29. # argument was an image.
  30. if im1.im.mode in ("1", "L"):
  31. return im1.im.convert("I")
  32. elif im1.im.mode in ("I", "F"):
  33. return im1.im
  34. else:
  35. raise ValueError(f"unsupported mode: {im1.im.mode}")
  36. else:
  37. # argument was a constant
  38. if _isconstant(im1) and self.im.mode in ("1", "L", "I"):
  39. return Image.new("I", self.im.size, im1)
  40. else:
  41. return Image.new("F", self.im.size, im1)
  42. def apply(self, op, im1, im2=None, mode=None):
  43. im1 = self.__fixup(im1)
  44. if im2 is None:
  45. # unary operation
  46. out = Image.new(mode or im1.mode, im1.size, None)
  47. im1.load()
  48. try:
  49. op = getattr(_imagingmath, op + "_" + im1.mode)
  50. except AttributeError as e:
  51. raise TypeError(f"bad operand type for '{op}'") from e
  52. _imagingmath.unop(op, out.im.id, im1.im.id)
  53. else:
  54. # binary operation
  55. im2 = self.__fixup(im2)
  56. if im1.mode != im2.mode:
  57. # convert both arguments to floating point
  58. if im1.mode != "F":
  59. im1 = im1.convert("F")
  60. if im2.mode != "F":
  61. im2 = im2.convert("F")
  62. if im1.mode != im2.mode:
  63. raise ValueError("mode mismatch")
  64. if im1.size != im2.size:
  65. # crop both arguments to a common size
  66. size = (min(im1.size[0], im2.size[0]), min(im1.size[1], im2.size[1]))
  67. if im1.size != size:
  68. im1 = im1.crop((0, 0) + size)
  69. if im2.size != size:
  70. im2 = im2.crop((0, 0) + size)
  71. out = Image.new(mode or im1.mode, size, None)
  72. else:
  73. out = Image.new(mode or im1.mode, im1.size, None)
  74. im1.load()
  75. im2.load()
  76. try:
  77. op = getattr(_imagingmath, op + "_" + im1.mode)
  78. except AttributeError as e:
  79. raise TypeError(f"bad operand type for '{op}'") from e
  80. _imagingmath.binop(op, out.im.id, im1.im.id, im2.im.id)
  81. return _Operand(out)
  82. # unary operators
  83. def __bool__(self):
  84. # an image is "true" if it contains at least one non-zero pixel
  85. return self.im.getbbox() is not None
  86. def __abs__(self):
  87. return self.apply("abs", self)
  88. def __pos__(self):
  89. return self
  90. def __neg__(self):
  91. return self.apply("neg", self)
  92. # binary operators
  93. def __add__(self, other):
  94. return self.apply("add", self, other)
  95. def __radd__(self, other):
  96. return self.apply("add", other, self)
  97. def __sub__(self, other):
  98. return self.apply("sub", self, other)
  99. def __rsub__(self, other):
  100. return self.apply("sub", other, self)
  101. def __mul__(self, other):
  102. return self.apply("mul", self, other)
  103. def __rmul__(self, other):
  104. return self.apply("mul", other, self)
  105. def __truediv__(self, other):
  106. return self.apply("div", self, other)
  107. def __rtruediv__(self, other):
  108. return self.apply("div", other, self)
  109. def __mod__(self, other):
  110. return self.apply("mod", self, other)
  111. def __rmod__(self, other):
  112. return self.apply("mod", other, self)
  113. def __pow__(self, other):
  114. return self.apply("pow", self, other)
  115. def __rpow__(self, other):
  116. return self.apply("pow", other, self)
  117. # bitwise
  118. def __invert__(self):
  119. return self.apply("invert", self)
  120. def __and__(self, other):
  121. return self.apply("and", self, other)
  122. def __rand__(self, other):
  123. return self.apply("and", other, self)
  124. def __or__(self, other):
  125. return self.apply("or", self, other)
  126. def __ror__(self, other):
  127. return self.apply("or", other, self)
  128. def __xor__(self, other):
  129. return self.apply("xor", self, other)
  130. def __rxor__(self, other):
  131. return self.apply("xor", other, self)
  132. def __lshift__(self, other):
  133. return self.apply("lshift", self, other)
  134. def __rshift__(self, other):
  135. return self.apply("rshift", self, other)
  136. # logical
  137. def __eq__(self, other):
  138. return self.apply("eq", self, other)
  139. def __ne__(self, other):
  140. return self.apply("ne", self, other)
  141. def __lt__(self, other):
  142. return self.apply("lt", self, other)
  143. def __le__(self, other):
  144. return self.apply("le", self, other)
  145. def __gt__(self, other):
  146. return self.apply("gt", self, other)
  147. def __ge__(self, other):
  148. return self.apply("ge", self, other)
  149. # conversions
  150. def imagemath_int(self):
  151. return _Operand(self.im.convert("I"))
  152. def imagemath_float(self):
  153. return _Operand(self.im.convert("F"))
  154. # logical
  155. def imagemath_equal(self, other):
  156. return self.apply("eq", self, other, mode="I")
  157. def imagemath_notequal(self, other):
  158. return self.apply("ne", self, other, mode="I")
  159. def imagemath_min(self, other):
  160. return self.apply("min", self, other)
  161. def imagemath_max(self, other):
  162. return self.apply("max", self, other)
  163. def imagemath_convert(self, mode):
  164. return _Operand(self.im.convert(mode))
  165. ops = {}
  166. for k, v in list(globals().items()):
  167. if k[:10] == "imagemath_":
  168. ops[k[10:]] = v
  169. def eval(expression, _dict={}, **kw):
  170. """
  171. Evaluates an image expression.
  172. :param expression: A string containing a Python-style expression.
  173. :param options: Values to add to the evaluation context. You
  174. can either use a dictionary, or one or more keyword
  175. arguments.
  176. :return: The evaluated expression. This is usually an image object, but can
  177. also be an integer, a floating point value, or a pixel tuple,
  178. depending on the expression.
  179. """
  180. # build execution namespace
  181. args = ops.copy()
  182. args.update(_dict)
  183. args.update(kw)
  184. for k, v in list(args.items()):
  185. if hasattr(v, "im"):
  186. args[k] = _Operand(v)
  187. out = builtins.eval(expression, args)
  188. try:
  189. return out.im
  190. except AttributeError:
  191. return out