Pillow/src/PIL/ImageMath.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

276 lines
8.7 KiB
Python
Raw Normal View History

2010-07-31 06:52:47 +04:00
#
# 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
2010-07-31 06:52:47 +04:00
2019-09-26 15:12:28 +03:00
import builtins
2024-01-10 14:05:26 +03:00
from typing import Any
2019-03-21 16:28:20 +03:00
2019-09-26 15:12:28 +03:00
from . import Image, _imagingmath
2014-07-05 13:13:43 +04:00
class _Operand:
2016-05-24 10:36:14 +03:00
"""Wraps an image operand, providing standard operators"""
2010-07-31 06:52:47 +04:00
2024-01-10 14:05:26 +03:00
def __init__(self, im: Image.Image):
2010-07-31 06:52:47 +04:00
self.im = im
2024-01-10 14:05:26 +03:00
def __fixup(self, im1: _Operand | float) -> Image.Image:
2010-07-31 06:52:47 +04:00
# 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)
2010-07-31 06:52:47 +04:00
else:
# argument was a constant
2023-12-18 19:11:29 +03:00
if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):
2010-07-31 06:52:47 +04:00
return Image.new("I", self.im.size, im1)
else:
return Image.new("F", self.im.size, im1)
2024-01-10 14:05:26 +03:00
def apply(
self,
op: str,
im1: _Operand | float,
im2: _Operand | float | None = None,
mode: str | None = None,
) -> _Operand:
im_1 = self.__fixup(im1)
2010-07-31 06:52:47 +04:00
if im2 is None:
# unary operation
2024-01-10 14:05:26 +03:00
out = Image.new(mode or im_1.mode, im_1.size, None)
im_1.load()
2010-07-31 06:52:47 +04:00
try:
2024-01-10 14:05:26 +03:00
op = getattr(_imagingmath, op + "_" + im_1.mode)
except AttributeError as e:
msg = f"bad operand type for '{op}'"
raise TypeError(msg) from e
2024-01-10 14:05:26 +03:00
_imagingmath.unop(op, out.im.id, im_1.im.id)
2010-07-31 06:52:47 +04:00
else:
# binary operation
2024-01-10 14:05:26 +03:00
im_2 = self.__fixup(im2)
if im_1.mode != im_2.mode:
2010-07-31 06:52:47 +04:00
# convert both arguments to floating point
2024-01-10 14:05:26 +03:00
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:
2010-07-31 06:52:47 +04:00
# crop both arguments to a common size
2024-01-10 14:05:26 +03:00
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()
2010-07-31 06:52:47 +04:00
try:
2024-01-10 14:05:26 +03:00
op = getattr(_imagingmath, op + "_" + im_1.mode)
except AttributeError as e:
msg = f"bad operand type for '{op}'"
raise TypeError(msg) from e
2024-01-10 14:05:26 +03:00
_imagingmath.binop(op, out.im.id, im_1.im.id, im_2.im.id)
2010-07-31 06:52:47 +04:00
return _Operand(out)
# unary operators
2024-01-10 14:05:26 +03:00
def __bool__(self) -> bool:
# an image is "true" if it contains at least one non-zero pixel
return self.im.getbbox() is not None
2024-01-10 14:05:26 +03:00
def __abs__(self) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("abs", self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __pos__(self) -> _Operand:
2010-07-31 06:52:47 +04:00
return self
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __neg__(self) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("neg", self)
# binary operators
2024-01-10 14:05:26 +03:00
def __add__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("add", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __radd__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("add", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __sub__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("sub", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rsub__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("sub", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __mul__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("mul", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rmul__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("mul", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __truediv__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("div", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rtruediv__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("div", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __mod__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("mod", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rmod__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("mod", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __pow__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("pow", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rpow__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("pow", other, self)
# bitwise
2024-01-10 14:05:26 +03:00
def __invert__(self) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("invert", self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __and__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("and", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rand__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("and", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __or__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("or", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __ror__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("or", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __xor__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("xor", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rxor__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("xor", other, self)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __lshift__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("lshift", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __rshift__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("rshift", self, other)
# logical
def __eq__(self, other):
return self.apply("eq", self, other)
2014-07-05 13:13:43 +04:00
2010-07-31 06:52:47 +04:00
def __ne__(self, other):
return self.apply("ne", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __lt__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("lt", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __le__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("le", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __gt__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("gt", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def __ge__(self, other: _Operand | float) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("ge", self, other)
2014-07-05 13:13:43 +04:00
2010-07-31 06:52:47 +04:00
# conversions
2024-01-10 14:05:26 +03:00
def imagemath_int(self: _Operand) -> _Operand:
2010-07-31 06:52:47 +04:00
return _Operand(self.im.convert("I"))
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def imagemath_float(self: _Operand) -> _Operand:
2010-07-31 06:52:47 +04:00
return _Operand(self.im.convert("F"))
2014-07-05 13:13:43 +04:00
2010-07-31 06:52:47 +04:00
# logical
2024-01-10 14:05:26 +03:00
def imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("eq", self, other, mode="I")
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("ne", self, other, mode="I")
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("min", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:
2010-07-31 06:52:47 +04:00
return self.apply("max", self, other)
2014-07-05 13:13:43 +04:00
2024-01-10 14:05:26 +03:00
def imagemath_convert(self: _Operand, mode: str) -> _Operand:
2010-07-31 06:52:47 +04:00
return _Operand(self.im.convert(mode))
2018-03-03 12:54:00 +03:00
2010-07-31 06:52:47 +04:00
ops = {}
for k, v in list(globals().items()):
2010-07-31 06:52:47 +04:00
if k[:10] == "imagemath_":
ops[k[10:]] = v
2024-01-10 14:05:26 +03:00
def eval(expression: str, _dict: dict[str, Any] = {}, **kw: Any) -> Any:
2013-10-13 04:40:14 +04:00
"""
Evaluates an image expression.
: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.
"""
2010-07-31 06:52:47 +04:00
# build execution namespace
args = ops.copy()
2023-10-28 07:58:52 +03:00
for k in list(_dict.keys()) + list(kw.keys()):
2023-12-30 01:30:12 +03:00
if "__" in k or hasattr(builtins, k):
msg = f"'{k}' not allowed"
raise ValueError(msg)
2023-10-28 07:58:52 +03:00
args.update(_dict)
args.update(kw)
for k, v in args.items():
2010-07-31 06:52:47 +04:00
if hasattr(v, "im"):
args[k] = _Operand(v)
compiled_code = compile(expression, "<string>", "eval")
2022-01-02 09:23:49 +03:00
2024-01-10 14:05:26 +03:00
def scan(code) -> None:
for const in code.co_consts:
2023-08-08 01:44:03 +03:00
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)
2022-01-02 09:23:49 +03:00
out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
2010-07-31 06:52:47 +04:00
try:
return out.im
except AttributeError:
return out