Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/ImageMath.py: 30%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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#
17from __future__ import annotations
19import builtins
21from . import Image, _imagingmath
23TYPE_CHECKING = False
24if TYPE_CHECKING:
25 from collections.abc import Callable
26 from types import CodeType
27 from typing import Any
30class _Operand:
31 """Wraps an image operand, providing standard operators"""
33 def __init__(self, im: Image.Image):
34 self.im = im
36 def __fixup(self, im1: _Operand | float) -> Image.Image:
37 # convert image to suitable mode
38 if isinstance(im1, _Operand):
39 # argument was an image.
40 if im1.im.mode in ("1", "L"):
41 return im1.im.convert("I")
42 elif im1.im.mode in ("I", "F"):
43 return im1.im
44 else:
45 msg = f"unsupported mode: {im1.im.mode}"
46 raise ValueError(msg)
47 else:
48 # argument was a constant
49 if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
50 return Image.new("I", self.im.size, im1)
51 else:
52 return Image.new("F", self.im.size, im1)
54 def apply(
55 self,
56 op: str,
57 im1: _Operand | float,
58 im2: _Operand | float | None = None,
59 mode: str | None = None,
60 ) -> _Operand:
61 im_1 = self.__fixup(im1)
62 if im2 is None:
63 # unary operation
64 out = Image.new(mode or im_1.mode, im_1.size, None)
65 try:
66 op = getattr(_imagingmath, f"{op}_{im_1.mode}")
67 except AttributeError as e:
68 msg = f"bad operand type for '{op}'"
69 raise TypeError(msg) from e
70 _imagingmath.unop(op, out.getim(), im_1.getim())
71 else:
72 # binary operation
73 im_2 = self.__fixup(im2)
74 if im_1.mode != im_2.mode:
75 # convert both arguments to floating point
76 if im_1.mode != "F":
77 im_1 = im_1.convert("F")
78 if im_2.mode != "F":
79 im_2 = im_2.convert("F")
80 if im_1.size != im_2.size:
81 # crop both arguments to a common size
82 size = (
83 min(im_1.size[0], im_2.size[0]),
84 min(im_1.size[1], im_2.size[1]),
85 )
86 if im_1.size != size:
87 im_1 = im_1.crop((0, 0) + size)
88 if im_2.size != size:
89 im_2 = im_2.crop((0, 0) + size)
90 out = Image.new(mode or im_1.mode, im_1.size, None)
91 try:
92 op = getattr(_imagingmath, f"{op}_{im_1.mode}")
93 except AttributeError as e:
94 msg = f"bad operand type for '{op}'"
95 raise TypeError(msg) from e
96 _imagingmath.binop(op, out.getim(), im_1.getim(), im_2.getim())
97 return _Operand(out)
99 # unary operators
100 def __bool__(self) -> bool:
101 # an image is "true" if it contains at least one non-zero pixel
102 return self.im.getbbox() is not None
104 def __abs__(self) -> _Operand:
105 return self.apply("abs", self)
107 def __pos__(self) -> _Operand:
108 return self
110 def __neg__(self) -> _Operand:
111 return self.apply("neg", self)
113 # binary operators
114 def __add__(self, other: _Operand | float) -> _Operand:
115 return self.apply("add", self, other)
117 def __radd__(self, other: _Operand | float) -> _Operand:
118 return self.apply("add", other, self)
120 def __sub__(self, other: _Operand | float) -> _Operand:
121 return self.apply("sub", self, other)
123 def __rsub__(self, other: _Operand | float) -> _Operand:
124 return self.apply("sub", other, self)
126 def __mul__(self, other: _Operand | float) -> _Operand:
127 return self.apply("mul", self, other)
129 def __rmul__(self, other: _Operand | float) -> _Operand:
130 return self.apply("mul", other, self)
132 def __truediv__(self, other: _Operand | float) -> _Operand:
133 return self.apply("div", self, other)
135 def __rtruediv__(self, other: _Operand | float) -> _Operand:
136 return self.apply("div", other, self)
138 def __mod__(self, other: _Operand | float) -> _Operand:
139 return self.apply("mod", self, other)
141 def __rmod__(self, other: _Operand | float) -> _Operand:
142 return self.apply("mod", other, self)
144 def __pow__(self, other: _Operand | float) -> _Operand:
145 return self.apply("pow", self, other)
147 def __rpow__(self, other: _Operand | float) -> _Operand:
148 return self.apply("pow", other, self)
150 # bitwise
151 def __invert__(self) -> _Operand:
152 return self.apply("invert", self)
154 def __and__(self, other: _Operand | float) -> _Operand:
155 return self.apply("and", self, other)
157 def __rand__(self, other: _Operand | float) -> _Operand:
158 return self.apply("and", other, self)
160 def __or__(self, other: _Operand | float) -> _Operand:
161 return self.apply("or", self, other)
163 def __ror__(self, other: _Operand | float) -> _Operand:
164 return self.apply("or", other, self)
166 def __xor__(self, other: _Operand | float) -> _Operand:
167 return self.apply("xor", self, other)
169 def __rxor__(self, other: _Operand | float) -> _Operand:
170 return self.apply("xor", other, self)
172 def __lshift__(self, other: _Operand | float) -> _Operand:
173 return self.apply("lshift", self, other)
175 def __rshift__(self, other: _Operand | float) -> _Operand:
176 return self.apply("rshift", self, other)
178 # logical
179 def __eq__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
180 return self.apply("eq", self, other)
182 def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override]
183 return self.apply("ne", self, other)
185 def __lt__(self, other: _Operand | float) -> _Operand:
186 return self.apply("lt", self, other)
188 def __le__(self, other: _Operand | float) -> _Operand:
189 return self.apply("le", self, other)
191 def __gt__(self, other: _Operand | float) -> _Operand:
192 return self.apply("gt", self, other)
194 def __ge__(self, other: _Operand | float) -> _Operand:
195 return self.apply("ge", self, other)
198# conversions
199def imagemath_int(self: _Operand) -> _Operand:
200 return _Operand(self.im.convert("I"))
203def imagemath_float(self: _Operand) -> _Operand:
204 return _Operand(self.im.convert("F"))
207# logical
208def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
209 return self.apply("eq", self, other, mode="I")
212def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
213 return self.apply("ne", self, other, mode="I")
216def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
217 return self.apply("min", self, other)
220def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
221 return self.apply("max", self, other)
224def imagemath_convert(self: _Operand, mode: str) -> _Operand:
225 return _Operand(self.im.convert(mode))
228ops = {
229 "int": imagemath_int,
230 "float": imagemath_float,
231 "equal": imagemath_equal,
232 "notequal": imagemath_notequal,
233 "min": imagemath_min,
234 "max": imagemath_max,
235 "convert": imagemath_convert,
236}
239def lambda_eval(expression: Callable[[dict[str, Any]], Any], **kw: Any) -> Any:
240 """
241 Returns the result of an image function.
243 :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
244 images, use the :py:meth:`~PIL.Image.Image.split` method or
245 :py:func:`~PIL.Image.merge` function.
247 :param expression: A function that receives a dictionary.
248 :param **kw: Values to add to the function's dictionary.
249 :return: The expression result. This is usually an image object, but can
250 also be an integer, a floating point value, or a pixel tuple,
251 depending on the expression.
252 """
254 args: dict[str, Any] = ops.copy()
255 args.update(kw)
256 for k, v in args.items():
257 if isinstance(v, Image.Image):
258 args[k] = _Operand(v)
260 out = expression(args)
261 try:
262 return out.im
263 except AttributeError:
264 return out
267def unsafe_eval(expression: str, **kw: Any) -> Any:
268 """
269 Evaluates an image expression. This uses Python's ``eval()`` function to process
270 the expression string, and carries the security risks of doing so. It is not
271 recommended to process expressions without considering this.
272 :py:meth:`~lambda_eval` is a more secure alternative.
274 :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
275 images, use the :py:meth:`~PIL.Image.Image.split` method or
276 :py:func:`~PIL.Image.merge` function.
278 :param expression: A string containing a Python-style expression.
279 :param **kw: Values to add to the evaluation context.
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 """
285 # build execution namespace
286 args: dict[str, Any] = ops.copy()
287 for k in kw:
288 if "__" in k or hasattr(builtins, k):
289 msg = f"'{k}' not allowed"
290 raise ValueError(msg)
292 args.update(kw)
293 for k, v in args.items():
294 if isinstance(v, Image.Image):
295 args[k] = _Operand(v)
297 compiled_code = compile(expression, "<string>", "eval")
299 def scan(code: CodeType) -> None:
300 for const in code.co_consts:
301 if type(const) is type(compiled_code):
302 scan(const)
304 for name in code.co_names:
305 if name not in args and name != "abs":
306 msg = f"'{name}' not allowed"
307 raise ValueError(msg)
309 scan(compiled_code)
310 out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
311 try:
312 return out.im
313 except AttributeError:
314 return out