Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中将一个图像乘以另一个图像_Python_Image_Python 2.7_Python Imaging Library - Fatal编程技术网

如何在python中将一个图像乘以另一个图像

如何在python中将一个图像乘以另一个图像,python,image,python-2.7,python-imaging-library,Python,Image,Python 2.7,Python Imaging Library,我正在尝试获得一个图像,而不是另一个图像,即如果我有两个图像greenapple.png和redcolor.png,现在我想将redcolor.png乘以greenapple.png,这样greenapple.png中的图像将仅在greenapple.png所在的位置被redcolor.png覆盖,剩下的部分就不用了。 我试过ImageChops来做,代码是 import Image import bakepass from PIL import ImageChops im1 = Image.

我正在尝试获得一个图像,而不是另一个图像,即如果我有两个图像greenapple.png和redcolor.png,现在我想将redcolor.png乘以greenapple.png,这样greenapple.png中的图像将仅在greenapple.png所在的位置被redcolor.png覆盖,剩下的部分就不用了。 我试过ImageChops来做,代码是

import Image
import bakepass
from PIL import ImageChops

im1 = Image.open("greenapple.png")
im2 = Image.open("redcolor.png")
image = Image.open("new.png")

image.save(ImageChops.multiply(im1,im2))
但是使用上面的代码我得到了一个值错误:图像不匹配 我正在使用大小相同的512X512文件
请帮帮我这可能就是你想要的:

但是,如果出于某种原因不想使用numpy,可以使用合成和alpha通道(下面在整个图像中放置alpha值,您可以通过img1的绿色/红色计算更改img2的alpha的位置):

下面是我在上面的测试中使用的两个图像(可能有点大),第三个图像是上面代码的结果:

apple.png

green.png

out.png

还有PIL的
paste()
函数:

from PIL import Image, ImageEnhance
img = Image.open('greenapple.png', 'r')
img_w, img_h = img.size

red = Image.open('redcolor.png', 'r')
# red_w, red_h = red.size

new = Image.new('RGBA', (1024,769), (255, 255, 255, 255))
new_w, new_h = new.size
offset=((new_w-img_w)/2,(new_h-img_h)/2)

red.putalpha(ImageEnhance.Brightness(red.split()[3]).enhance(0.75))

new.paste(img, offset)
new.paste(red, offset)
new.save('out.png')
玩一下
img.split()
,它会为您提供
红色、绿色、蓝色、alpha
,并在确定覆盖的位置时使用绿色/红色补丁

以下是一些计算量更大的备选方案,例如,您可以使用黑色作为排除颜色:


我已检查过,没有错误,但图像没有更改also@user3453803检查我的编辑,忘记添加alpha,而且合成图上img2/img1的顺序已关闭。再一次,对不起,我脑子里的代码太多了,做起来有点棘手:)谢谢你这么清楚的描述,先生,但是我们能不能把苹果出现的区域显示为绿色,然后离开屏幕rest@user3453803要么创建与要覆盖的零件大小相同的覆盖,要么从
img.getpixel((x,y))获取红色通道
并在覆盖上循环,仅读取与第一幅图像中的红色通道匹配的
(x,y)
。这是你必须要做的手工工作,PIL中没有预定义的函数(因此我的参考链接)它抛出一个错误“NoneType”对象没有来自PIL导入图像的属性“bands”
。另见:
from PIL import Image, ImageEnhance
img = Image.open('greenapple.png', 'r')
img_w, img_h = img.size

red = Image.open('redcolor.png', 'r')
# red_w, red_h = red.size

new = Image.new('RGBA', (1024,769), (255, 255, 255, 255))
new_w, new_h = new.size
offset=((new_w-img_w)/2,(new_h-img_h)/2)

red.putalpha(ImageEnhance.Brightness(red.split()[3]).enhance(0.75))

new.paste(img, offset)
new.paste(red, offset)
new.save('out.png')