Python PIL | ImageMath.eval() 方法
PIL 是Python Imaging Library,它为Python解释器提供了图像编辑功能。该模块还提供了许多工厂函数,包括从文件加载图像和创建新图像的函数。
ImageMath
模块可用于评估“图像表达式”。该模块提供了一个 eval函数,它接受一个表达式字符串和一个或多个图像。
PIL.ImageMath.eval()
在给定环境中计算表达式。
在当前版本中,ImageMath 仅支持单层图像。要处理多波段图像,请使用 split() 方法或 merge()函数。
Syntax: PIL.ImageMath.eval(expression, environment)
Parameters:
expression – A string which uses the standard Python expression syntax. In addition to the standard operators, you can also use the functions described below.
environment – A dictionary that maps image names to Image instances. You can use one or more keyword arguments instead of a dictionary, as shown in the above example. Note that the names must be valid Python identifiers.
Returns type: An image, an integer value, a floating point value, or a pixel tuple, depending on the expression.
使用的图像1:
使用的图像2:
# Importing Image module from PIL package
from PIL import Image, ImageMath
# creating a image object
im1 = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg").convert('L')
im2 = Image.open(r"C:\Users\System-Pc\Desktop\leave.jpg").convert('L')
# applying the eval method
out = ImageMath.eval("convert(min(a, b), 'L')", a = im1, b = im2)
out.save("result.jpg")
out.show()
输出:
另一个例子:这里我们将内置的 min() 更改为 max()。
# Importing Image module from PIL package
from PIL import Image, ImageMath
# creating a image object
im1 = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg").convert('L')
im2 = Image.open(r"C:\Users\System-Pc\Desktop\leave.jpg").convert('L')
# applying the eval method
out = ImageMath.eval("convert(max(a, b), 'L')", a = im1, b = im2)
out.save("result.jpg")
out.show()
输出: