Python PIL - 划分混合两个图像的功能?

标签 python image-processing overlay python-imaging-library blend

编辑:代码现在可以运行了,感谢 Mark 和 zephyr。 zephyr 在下面还有两个替代的工作解决方案。

我想用 PIL 分割混合两个图像。我找到了 ImageChops.multiply(image1, image2) 但找不到类似的 divide(image, image2) 函数。

Divide Blend Mode Explained (我在这里使用前两张图片作为我的测试源。)

是否有我错过的内置除法混合函数(PIL 或其他)?

我下面的测试代码运行并且越来越接近我正在寻找的东西。生成的图像输出类似于此处的分割混合示例图像:Divide Blend Mode Explained .

是否有更有效的方法来执行此除法混合操作(步骤更少且速度更快)?起初,我尝试在 Image.evalImageMath.eval 中使用 lambda 函数来检查黑色像素并在除法过程中将它们翻转为白色,但我做不到获取其中一个以产生正确的结果。

编辑:修复代码并缩短代码,感谢 Mark 和 zephyr。生成的图像输出与以下 zephyr 的 numpy 和 scipy 解决方案的输出相匹配。

# PIL Divide Blend test

import Image, os, ImageMath

imgA = Image.open('01background.jpg')
imgA.load()
imgB = Image.open('02testgray.jpg')
imgB.load()

# split RGB images into 3 channels
rA, gA, bA = imgA.split()
rB, gB, bB = imgB.split()

# divide each channel (image1/image2)
rTmp = ImageMath.eval("int(a/((float(b)+1)/256))", a=rA, b=rB).convert('L')
gTmp = ImageMath.eval("int(a/((float(b)+1)/256))", a=gA, b=gB).convert('L')
bTmp = ImageMath.eval("int(a/((float(b)+1)/256))", a=bA, b=bB).convert('L')

# merge channels into RGB image
imgOut = Image.merge("RGB", (rTmp, gTmp, bTmp))

imgOut.save('PILdiv0.png', 'PNG')

os.system('start PILdiv0.png')

最佳答案

你在问:

Is there a more efficient way to do this divide blend operation (less steps and faster)?

您还可以使用 python 包 blend modes .它是用向量化的 Numpy 数学编写的,通常速度很快。通过 pip install blend_modes 安装它。我以更冗长的方式编写命令以提高可读性,将它们链接起来会更短。像这样使用 blend_modes 来分割图像:

from PIL import Image
import numpy
import os
from blend_modes import blend_modes

# Load images
imgA = Image.open('01background.jpg')
imgA = numpy.array(imgA)
# append alpha channel
imgA = numpy.dstack((imgA, numpy.ones((imgA.shape[0], imgA.shape[1], 1))*255))
imgA = imgA.astype(float)

imgB = Image.open('02testgray.jpg')
imgB = numpy.array(imgB)
# append alpha channel
imgB = numpy.dstack((imgB, numpy.ones((imgB.shape[0], imgB.shape[1], 1))*255))
imgB = imgB.astype(float)

# Divide images
imgOut = blend_modes.divide(imgA, imgB, 1.0)

# Save images
imgOut = numpy.uint8(imgOut)
imgOut = Image.fromarray(imgOut)
imgOut.save('PILdiv0.png', 'PNG')

os.system('start PILdiv0.png')

请注意,要使其正常工作,两个图像需要具有相同的尺寸,例如imgA.shape == (240,320,3)imgB.shape == (240,320,3)

关于Python PIL - 划分混合两个图像的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605174/

相关文章:

image-processing - 使用 Kinect 进行人脸识别

c++ - 如何将提取的栅格信息转换为opencv库可处理的格式

html - 在 float 图像上叠加下拉菜单

python - 在 Python 中使用重复项列出索引

matlab - 如何更改相机参数(自动曝光、快门速度、增益)?

python - 如何从列表中删除每 12 个零

html - 如何阻止 css 覆盖文本

android - Android 应用程序中 Google map 上的 KML

Python Selenium 按名称查找元素

python - Pandas 插值在最后一个数据点之后替换 NaN,但不在第一个数据点之前