You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

271 lines
7.3 KiB

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