我有一张PNG图像和一个黑白面具.这篇文章(https://note.nkmk.me/en/python-pillow-putalpha/)演示了如何使用putalpha()发送图像的Alpha通道,以便遮罩区域变得透明.我想知道Pillow中是否有函数可以真正将遮罩区域的RGB值更改为全部255?

下面是一个例子.结果图像应该具有实际RGB值为255的所有白色区域,而不是仅将Alpha设置为0.

The original image The mask The image I want to get, the white area should have RGB value of 255.

Updated question

(当我try 使用ImageChops时,遇到了一些错误:

下面是我运行的代码:

from PIL import Image, ImageChops

im = Image.open('lena.jpg')
mask = Image.open('mask_circle.png')

print(im, mask)
darker = ImageChops.darker(im, mask)
darker.save('darker.png')

我得到的错误是:

<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=400x225 at 0x24725330BF0> <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=400x225 at 0x24724F2CD40>
Traceback (most recent call last):
  File "E:\test.py", line 7, in <module>
    darker = ImageChops.darker(im, mask)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\...\Local\Programs\Python\Python312\Lib\site-packages\PIL\ImageChops.py", line 81, in darker
    return image1._new(image1.im.chop_darker(image2.im))
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: images do not match

推荐答案

Updated Answer

也许@ChristophRackwitz已经在 comments 中推断出你想要的东西--实际上是将透明像素置零,这样如果后来有人删除了Alpha/透明通道,它们就无法恢复.如果是这样,您可以使用:

from PIL import Image, ImageChops

# Load image and mask
im = Image.open('lena.jpg')
mask = Image.open('mask.png')

# Zero out all areas that will become transparent
darker = ImageChops.darker(im,mask)

enter image description here

# Push alpha channel to make surrounding area transparent
darker.putalpha(mask.convert('L'))
darker.save('result.png')

enter image description here


Original Answer

你的问题对我来说没有多大意义.如果在蒙版中将RGB值设置为255,图像将变为白色,最终将得到蒙版-您已经拥有了蒙版.

也许你的意思是,你想保留Lena图片的其余部分,但只将Face设置为白色,并保留图像"as is"的其余部分.如果是这种情况,你可以使用100混合模式,它只会在两张图片中的每个位置 Select 更亮的像素-所以它会在蒙版为白色的地方 Select 白色,在其他地方 Select 莉娜,因为这肯定会比蒙版的黑色更亮:

PIL import Image, ImageChops

# Load image and mask
im = Image.open('lena.jpg')
mask = Image.open('mask.png')

# Select whichever is lighter at each pixel location
res = ImageChops.lighter(im,mask)
res.save('result.png')

enter image description here

Python相关问答推荐

如何请求使用Python将文件下载到带有登录名的门户网站?

如何使用它?

实现自定义QWidgets作为QTimeEdit的弹出窗口

所有列的滚动标准差,忽略NaN

driver. find_element无法通过class_name找到元素'""

在pandas中使用group_by,但有条件

为什么\b在这个正则表达式中不解释为反斜杠

未调用自定义JSON编码器

如何找出Pandas 图中的连续空值(NaN)?

在代码执行后关闭ChromeDriver窗口

在numpy数组中寻找楼梯状 struct

什么是一种快速而优雅的方式来转换一个包含一串重复的列,而不对同一个值多次运行转换,

如何反转一个框架中列的值?

Django在一个不是ForeignKey的字段上加入'

操作布尔值的Series时出现索引问题

随机森林n_估计器的计算

按条件计算将记录拆分成两条记录

EST格式的Azure数据库笔记本中的当前时间戳

Pandas ,快速从词典栏中提取信息到新栏

生产者/消费者-Queue.get by list