ImageMath.py 12 KB

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