File size: 11,480 Bytes
e00b837
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#
# The Python Imaging Library
# $Id$
#
# a simple math add-on for the Python Imaging Library
#
# History:
# 1999-02-15 fl   Original PIL Plus release
# 2005-05-05 fl   Simplified and cleaned up for PIL 1.1.6
# 2005-09-12 fl   Fixed int() and float() for Python 2.4.1
#
# Copyright (c) 1999-2005 by Secret Labs AB
# Copyright (c) 2005 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from __future__ import annotations

import builtins
from types import CodeType
from typing import Any, Callable

from . import Image, _imagingmath
from ._deprecate import deprecate


class _Operand:
    """Wraps an image operand, providing standard operators"""

    def __init__(self, im: Image.Image):
        self.im = im

    def __fixup(self, im1: _Operand | float) -> Image.Image:
        # convert image to suitable mode
        if isinstance(im1, _Operand):
            # argument was an image.
            if im1.im.mode in ("1", "L"):
                return im1.im.convert("I")
            elif im1.im.mode in ("I", "F"):
                return im1.im
            else:
                msg = f"unsupported mode: {im1.im.mode}"
                raise ValueError(msg)
        else:
            # argument was a constant
            if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
                return Image.new("I", self.im.size, im1)
            else:
                return Image.new("F", self.im.size, im1)

    def apply(
        self,
        op: str,
        im1: _Operand | float,
        im2: _Operand | float | None = None,
        mode: str | None = None,
    ) -> _Operand:
        im_1 = self.__fixup(im1)
        if im2 is None:
            # unary operation
            out = Image.new(mode or im_1.mode, im_1.size, None)
            im_1.load()
            try:
                op = getattr(_imagingmath, op + "_" + im_1.mode)
            except AttributeError as e:
                msg = f"bad operand type for '{op}'"
                raise TypeError(msg) from e
            _imagingmath.unop(op, out.im.id, im_1.im.id)
        else:
            # binary operation
            im_2 = self.__fixup(im2)
            if im_1.mode != im_2.mode:
                # convert both arguments to floating point
                if im_1.mode != "F":
                    im_1 = im_1.convert("F")
                if im_2.mode != "F":
                    im_2 = im_2.convert("F")
            if im_1.size != im_2.size:
                # crop both arguments to a common size
                size = (
                    min(im_1.size[0], im_2.size[0]),
                    min(im_1.size[1], im_2.size[1]),
                )
                if im_1.size != size:
                    im_1 = im_1.crop((0, 0) + size)
                if im_2.size != size:
                    im_2 = im_2.crop((0, 0) + size)
            out = Image.new(mode or im_1.mode, im_1.size, None)
            im_1.load()
            im_2.load()
            try:
                op = getattr(_imagingmath, op + "_" + im_1.mode)
            except AttributeError as e:
                msg = f"bad operand type for '{op}'"
                raise TypeError(msg) from e
            _imagingmath.binop(op, out.im.id, im_1.im.id, im_2.im.id)
        return _Operand(out)

    # unary operators
    def __bool__(self) -> bool:
        # an image is "true" if it contains at least one non-zero pixel
        return self.im.getbbox() is not None

    def __abs__(self) -> _Operand:
        return self.apply("abs", self)

    def __pos__(self) -> _Operand:
        return self

    def __neg__(self) -> _Operand:
        return self.apply("neg", self)

    # binary operators
    def __add__(self, other: _Operand | float) -> _Operand:
        return self.apply("add", self, other)

    def __radd__(self, other: _Operand | float) -> _Operand:
        return self.apply("add", other, self)

    def __sub__(self, other: _Operand | float) -> _Operand:
        return self.apply("sub", self, other)

    def __rsub__(self, other: _Operand | float) -> _Operand:
        return self.apply("sub", other, self)

    def __mul__(self, other: _Operand | float) -> _Operand:
        return self.apply("mul", self, other)

    def __rmul__(self, other: _Operand | float) -> _Operand:
        return self.apply("mul", other, self)

    def __truediv__(self, other: _Operand | float) -> _Operand:
        return self.apply("div", self, other)

    def __rtruediv__(self, other: _Operand | float) -> _Operand:
        return self.apply("div", other, self)

    def __mod__(self, other: _Operand | float) -> _Operand:
        return self.apply("mod", self, other)

    def __rmod__(self, other: _Operand | float) -> _Operand:
        return self.apply("mod", other, self)

    def __pow__(self, other: _Operand | float) -> _Operand:
        return self.apply("pow", self, other)

    def __rpow__(self, other: _Operand | float) -> _Operand:
        return self.apply("pow", other, self)

    # bitwise
    def __invert__(self) -> _Operand:
        return self.apply("invert", self)

    def __and__(self, other: _Operand | float) -> _Operand:
        return self.apply("and", self, other)

    def __rand__(self, other: _Operand | float) -> _Operand:
        return self.apply("and", other, self)

    def __or__(self, other: _Operand | float) -> _Operand:
        return self.apply("or", self, other)

    def __ror__(self, other: _Operand | float) -> _Operand:
        return self.apply("or", other, self)

    def __xor__(self, other: _Operand | float) -> _Operand:
        return self.apply("xor", self, other)

    def __rxor__(self, other: _Operand | float) -> _Operand:
        return self.apply("xor", other, self)

    def __lshift__(self, other: _Operand | float) -> _Operand:
        return self.apply("lshift", self, other)

    def __rshift__(self, other: _Operand | float) -> _Operand:
        return self.apply("rshift", self, other)

    # logical
    def __eq__(self, other):
        return self.apply("eq", self, other)

    def __ne__(self, other):
        return self.apply("ne", self, other)

    def __lt__(self, other: _Operand | float) -> _Operand:
        return self.apply("lt", self, other)

    def __le__(self, other: _Operand | float) -> _Operand:
        return self.apply("le", self, other)

    def __gt__(self, other: _Operand | float) -> _Operand:
        return self.apply("gt", self, other)

    def __ge__(self, other: _Operand | float) -> _Operand:
        return self.apply("ge", self, other)


# conversions
def imagemath_int(self: _Operand) -> _Operand:
    return _Operand(self.im.convert("I"))


def imagemath_float(self: _Operand) -> _Operand:
    return _Operand(self.im.convert("F"))


# logical
def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
    return self.apply("eq", self, other, mode="I")


def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
    return self.apply("ne", self, other, mode="I")


def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
    return self.apply("min", self, other)


def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
    return self.apply("max", self, other)


def imagemath_convert(self: _Operand, mode: str) -> _Operand:
    return _Operand(self.im.convert(mode))


ops = {
    "int": imagemath_int,
    "float": imagemath_float,
    "equal": imagemath_equal,
    "notequal": imagemath_notequal,
    "min": imagemath_min,
    "max": imagemath_max,
    "convert": imagemath_convert,
}


def lambda_eval(
    expression: Callable[[dict[str, Any]], Any],
    options: dict[str, Any] = {},
    **kw: Any,
) -> Any:
    """
    Returns the result of an image function.

    :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
    images, use the :py:meth:`~PIL.Image.Image.split` method or
    :py:func:`~PIL.Image.merge` function.

    :param expression: A function that receives a dictionary.
    :param options: Values to add to the function's dictionary. You
                    can either use a dictionary, or one or more keyword
                    arguments.
    :return: The expression result. This is usually an image object, but can
             also be an integer, a floating point value, or a pixel tuple,
             depending on the expression.
    """

    args: dict[str, Any] = ops.copy()
    args.update(options)
    args.update(kw)
    for k, v in args.items():
        if hasattr(v, "im"):
            args[k] = _Operand(v)

    out = expression(args)
    try:
        return out.im
    except AttributeError:
        return out


def unsafe_eval(
    expression: str,
    options: dict[str, Any] = {},
    **kw: Any,
) -> Any:
    """
    Evaluates an image expression. This uses Python's ``eval()`` function to process
    the expression string, and carries the security risks of doing so. It is not
    recommended to process expressions without considering this.
    :py:meth:`~lambda_eval` is a more secure alternative.

    :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band
    images, use the :py:meth:`~PIL.Image.Image.split` method or
    :py:func:`~PIL.Image.merge` function.

    :param expression: A string containing a Python-style expression.
    :param options: Values to add to the evaluation context.  You
                    can either use a dictionary, or one or more keyword
                    arguments.
    :return: The evaluated expression. This is usually an image object, but can
             also be an integer, a floating point value, or a pixel tuple,
             depending on the expression.
    """

    # build execution namespace
    args: dict[str, Any] = ops.copy()
    for k in list(options.keys()) + list(kw.keys()):
        if "__" in k or hasattr(builtins, k):
            msg = f"'{k}' not allowed"
            raise ValueError(msg)

    args.update(options)
    args.update(kw)
    for k, v in args.items():
        if hasattr(v, "im"):
            args[k] = _Operand(v)

    compiled_code = compile(expression, "<string>", "eval")

    def scan(code: CodeType) -> None:
        for const in code.co_consts:
            if type(const) is type(compiled_code):
                scan(const)

        for name in code.co_names:
            if name not in args and name != "abs":
                msg = f"'{name}' not allowed"
                raise ValueError(msg)

    scan(compiled_code)
    out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
    try:
        return out.im
    except AttributeError:
        return out


def eval(
    expression: str,
    _dict: dict[str, Any] = {},
    **kw: Any,
) -> Any:
    """
    Evaluates an image expression.

    Deprecated. Use lambda_eval() or unsafe_eval() instead.

    :param expression: A string containing a Python-style expression.
    :param _dict: Values to add to the evaluation context.  You
                  can either use a dictionary, or one or more keyword
                  arguments.
    :return: The evaluated expression. This is usually an image object, but can
             also be an integer, a floating point value, or a pixel tuple,
             depending on the expression.

    ..  deprecated:: 10.3.0
    """

    deprecate(
        "ImageMath.eval",
        12,
        "ImageMath.lambda_eval or ImageMath.unsafe_eval",
    )
    return unsafe_eval(expression, _dict, **kw)