ImageMath.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 __future__ import annotations
  18. import builtins
  19. from types import CodeType
  20. from typing import Any, Callable
  21. from . import Image, _imagingmath
  22. from ._deprecate import deprecate
  23. class _Operand:
  24. """Wraps an image operand, providing standard operators"""
  25. def __init__(self, im: Image.Image):
  26. self.im = im
  27. def __fixup(self, im1: _Operand | float) -> Image.Image:
  28. # convert image to suitable mode
  29. if isinstance(im1, _Operand):
  30. # argument was an image.
  31. if im1.im.mode in ("1", "L"):
  32. return im1.im.convert("I")
  33. elif im1.im.mode in ("I", "F"):
  34. return im1.im
  35. else:
  36. msg = f"unsupported mode: {im1.im.mode}"
  37. raise ValueError(msg)
  38. else:
  39. # argument was a constant
  40. if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
  41. return Image.new("I", self.im.size, im1)
  42. else:
  43. return Image.new("F", self.im.size, im1)
  44. def apply(
  45. self,
  46. op: str,
  47. im1: _Operand | float,
  48. im2: _Operand | float | None = None,
  49. mode: str | None = None,
  50. ) -> _Operand:
  51. im_1 = self.__fixup(im1)
  52. if im2 is None:
  53. # unary operation
  54. out = Image.new(mode or im_1.mode, im_1.size, None)
  55. im_1.load()
  56. try:
  57. op = getattr(_imagingmath, f"{op}_{im_1.mode}")
  58. except AttributeError as e:
  59. msg = f"bad operand type for '{op}'"
  60. raise TypeError(msg) from e
  61. _imagingmath.unop(op, out.im.id, im_1.im.id)
  62. else:
  63. # binary operation
  64. im_2 = self.__fixup(im2)
  65. if im_1.mode != im_2.mode:
  66. # convert both arguments to floating point
  67. if im_1.mode != "F":
  68. im_1 = im_1.convert("F")
  69. if im_2.mode != "F":
  70. im_2 = im_2.convert("F")
  71. if im_1.size != im_2.size:
  72. # crop both arguments to a common size
  73. size = (
  74. min(im_1.size[0], im_2.size[0]),
  75. min(im_1.size[1], im_2.size[1]),
  76. )
  77. if im_1.size != size:
  78. im_1 = im_1.crop((0, 0) + size)
  79. if im_2.size != size:
  80. im_2 = im_2.crop((0, 0) + size)
  81. out = Image.new(mode or im_1.mode, im_1.size, None)
  82. im_1.load()
  83. im_2.load()
  84. try:
  85. op = getattr(_imagingmath, f"{op}_{im_1.mode}")
  86. except AttributeError as e:
  87. msg = f"bad operand type for '{op}'"
  88. raise TypeError(msg) from e
  89. _imagingmath.binop(op, out.im.id, im_1.im.id, im_2.im.id)
  90. return _Operand(out)
  91. # unary operators
  92. def __bool__(self) -> bool:
  93. # an image is "true" if it contains at least one non-zero pixel
  94. return self.im.getbbox() is not None
  95. def __abs__(self) -> _Operand:
  96. return self.apply("abs", self)
  97. def __pos__(self) -> _Operand:
  98. return self
  99. def __neg__(self) -> _Operand:
  100. return self.apply("neg", self)
  101. # binary operators
  102. def __add__(self, other: _Operand | float) -> _Operand:
  103. return self.apply("add", self, other)
  104. def __radd__(self, other: _Operand | float) -> _Operand:
  105. return self.apply("add", other, self)
  106. def __sub__(self, other: _Operand | float) -> _Operand:
  107. return self.apply("sub", self, other)
  108. def __rsub__(self, other: _Operand | float) -> _Operand:
  109. return self.apply("sub", other, self)
  110. def __mul__(self, other: _Operand | float) -> _Operand:
  111. return self.apply("mul", self, other)
  112. def __rmul__(self, other: _Operand | float) -> _Operand:
  113. return self.apply("mul", other, self)
  114. def __truediv__(self, other: _Operand | float) -> _Operand:
  115. return self.apply("div", self, other)
  116. def __rtruediv__(self, other: _Operand | float) -> _Operand:
  117. return self.apply("div", other, self)
  118. def __mod__(self, other: _Operand | float) -> _Operand:
  119. return self.apply("mod", self, other)
  120. def __rmod__(self, other: _Operand | float) -> _Operand:
  121. return self.apply("mod", other, self)
  122. def __pow__(self, other: _Operand | float) -> _Operand:
  123. return self.apply("pow", self, other)
  124. def __rpow__(self, other: _Operand | float) -> _Operand:
  125. return self.apply("pow", other, self)
  126. # bitwise
  127. def __invert__(self) -> _Operand:
  128. return self.apply("invert", self)
  129. def __and__(self, other: _Operand | float) -> _Operand:
  130. return self.apply("and", self, other)
  131. def __rand__(self, other: _Operand | float) -> _Operand:
  132. return self.apply("and", other, self)
  133. def __or__(self, other: _Operand | float) -> _Operand:
  134. return self.apply("or", self, other)
  135. def __ror__(self, other: _Operand | float) -> _Operand:
  136. return self.apply("or", other, self)
  137. def __xor__(self, other: _Operand | float) -> _Operand:
  138. return self.apply("xor", self, other)
  139. def __rxor__(self, other: _Operand | float) -> _Operand:
  140. return self.apply("xor", other, self)
  141. def __lshift__(self, other: _Operand | float) -> _Operand:
  142. return self.apply("lshift", self, other)
  143. def __rshift__(self, other: _Operand | float) -> _Operand:
  144. return self.apply("rshift", self, other)
  145. # logical
  146. def __eq__(self, other):
  147. return self.apply("eq", self, other)
  148. def __ne__(self, other):
  149. return self.apply("ne", self, other)
  150. def __lt__(self, other: _Operand | float) -> _Operand:
  151. return self.apply("lt", self, other)
  152. def __le__(self, other: _Operand | float) -> _Operand:
  153. return self.apply("le", self, other)
  154. def __gt__(self, other: _Operand | float) -> _Operand:
  155. return self.apply("gt", self, other)
  156. def __ge__(self, other: _Operand | float) -> _Operand:
  157. return self.apply("ge", self, other)
  158. # conversions
  159. def imagemath_int(self: _Operand) -> _Operand:
  160. return _Operand(self.im.convert("I"))
  161. def imagemath_float(self: _Operand) -> _Operand:
  162. return _Operand(self.im.convert("F"))
  163. # logical
  164. def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
  165. return self.apply("eq", self, other, mode="I")
  166. def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
  167. return self.apply("ne", self, other, mode="I")
  168. def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
  169. return self.apply("min", self, other)
  170. def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
  171. return self.apply("max", self, other)
  172. def imagemath_convert(self: _Operand, mode: str) -> _Operand:
  173. return _Operand(self.im.convert(mode))
  174. ops = {
  175. "int": imagemath_int,
  176. "float": imagemath_float,
  177. "equal": imagemath_equal,
  178. "notequal": imagemath_notequal,
  179. "min": imagemath_min,
  180. "max": imagemath_max,
  181. "convert": imagemath_convert,
  182. }
  183. def lambda_eval(
  184. expression: Callable[[dict[str, Any]], Any],
  185. options: dict[str, Any] = {},
  186. **kw: Any,
  187. ) -> Any:
  188. """
  189. Returns the result of an image function.
  190. :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
  191. images, use the :py:meth:`~PIL.Image.Image.split` method or
  192. :py:func:`~PIL.Image.merge` function.
  193. :param expression: A function that receives a dictionary.
  194. :param options: Values to add to the function's dictionary. You
  195. can either use a dictionary, or one or more keyword
  196. arguments.
  197. :return: The expression result. This is usually an image object, but can
  198. also be an integer, a floating point value, or a pixel tuple,
  199. depending on the expression.
  200. """
  201. args: dict[str, Any] = ops.copy()
  202. args.update(options)
  203. args.update(kw)
  204. for k, v in args.items():
  205. if hasattr(v, "im"):
  206. args[k] = _Operand(v)
  207. out = expression(args)
  208. try:
  209. return out.im
  210. except AttributeError:
  211. return out
  212. def unsafe_eval(
  213. expression: str,
  214. options: dict[str, Any] = {},
  215. **kw: Any,
  216. ) -> Any:
  217. """
  218. Evaluates an image expression. This uses Python's ``eval()`` function to process
  219. the expression string, and carries the security risks of doing so. It is not
  220. recommended to process expressions without considering this.
  221. :py:meth:`~lambda_eval` is a more secure alternative.
  222. :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
  223. images, use the :py:meth:`~PIL.Image.Image.split` method or
  224. :py:func:`~PIL.Image.merge` function.
  225. :param expression: A string containing a Python-style expression.
  226. :param options: Values to add to the evaluation context. You
  227. can either use a dictionary, or one or more keyword
  228. arguments.
  229. :return: The evaluated expression. This is usually an image object, but can
  230. also be an integer, a floating point value, or a pixel tuple,
  231. depending on the expression.
  232. """
  233. # build execution namespace
  234. args: dict[str, Any] = ops.copy()
  235. for k in list(options.keys()) + list(kw.keys()):
  236. if "__" in k or hasattr(builtins, k):
  237. msg = f"'{k}' not allowed"
  238. raise ValueError(msg)
  239. args.update(options)
  240. args.update(kw)
  241. for k, v in args.items():
  242. if hasattr(v, "im"):
  243. args[k] = _Operand(v)
  244. compiled_code = compile(expression, "<string>", "eval")
  245. def scan(code: CodeType) -> None:
  246. for const in code.co_consts:
  247. if type(const) is type(compiled_code):
  248. scan(const)
  249. for name in code.co_names:
  250. if name not in args and name != "abs":
  251. msg = f"'{name}' not allowed"
  252. raise ValueError(msg)
  253. scan(compiled_code)
  254. out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
  255. try:
  256. return out.im
  257. except AttributeError:
  258. return out
  259. def eval(
  260. expression: str,
  261. _dict: dict[str, Any] = {},
  262. **kw: Any,
  263. ) -> Any:
  264. """
  265. Evaluates an image expression.
  266. Deprecated. Use lambda_eval() or unsafe_eval() instead.
  267. :param expression: A string containing a Python-style expression.
  268. :param _dict: Values to add to the evaluation context. You
  269. can either use a dictionary, or one or more keyword
  270. arguments.
  271. :return: The evaluated expression. This is usually an image object, but can
  272. also be an integer, a floating point value, or a pixel tuple,
  273. depending on the expression.
  274. .. deprecated:: 10.3.0
  275. """
  276. deprecate(
  277. "ImageMath.eval",
  278. 12,
  279. "ImageMath.lambda_eval or ImageMath.unsafe_eval",
  280. )
  281. return unsafe_eval(expression, _dict, **kw)