python-imaging-library - 如何使用PIL访问和更改颜色 channel ?

标签 python-imaging-library

我正在尝试使用PIL访问图像的RGB颜色 channel ,然后立即更改整个图像的颜色 channel 的颜色强度。

当我说RGB颜色 channel 时,here是一个在线示例。

我不知道是否必须逐个像素地完成此操作。

我认为代码的逻辑如下所示:

import PIL
from PIL import Image
image=Image.open("my_pic.gif")
image=image.convert('RGB')
# made up function
channel_values = image.get_channel_values()
#channel_values = i.e. (50, 100, 50)
# do some math function to transform channel_values
channel_values = (95,125,75)
image.update_channel_value('R',channel_values)
display(image.getchannel('R'))

This答案是唯一接近的答案,但是对于我想做的事情来说太复杂了。

我已经搜索了PIL文档等几个小时,但似乎什么也没找到。

这是我走了多远:
import PIL
from PIL import Image
image=Image.open("my_pic.gif")
image=image.convert('RGB')
display(image.getchannel('R'))

问题是image.getchannel()仅返回灰色/黑白图像。

我不仅要访问颜色 channel 值,也要更改它。

最佳答案

例如,如果要将红色 channel 中的所有像素乘以1.2,并将所有绿色像素乘以0.9,则可以有几种选择...。

将图像分为红色,绿色和蓝色 channel ,放大红色 channel 并重新组合:

from PIL import Image
im = Image.open('image.jpg').convert('RGB')

# Split into 3 channels
r, g, b = im.split()

# Increase Reds
r = r.point(lambda i: i * 1.2)

# Decrease Greens
g = g.point(lambda i: i * 0.9)

# Recombine back to RGB image
result = Image.merge('RGB', (r, g, b))

result.save('result.png')

请参见“处理单个频段” here

或者,使用矩阵来变换 channel :
from PIL import Image 

# Open image 
im = Image.open('image.jpg') 

# Make transform matrix, to multiply R by 1.1, G by 0.9 and leave B unchanged
# newRed   = 1.1*oldRed  +  0*oldGreen    +  0*oldBlue  + constant
# newGreen = 0*oldRed    +  0.9*OldGreen  +  0*OldBlue  + constant
# newBlue  = 0*oldRed    +  0*OldGreen    +  1*OldBlue  + constant
Matrix = ( 1.1,   0,  0, 0, 
           0,   0.9,  0, 0, 
           0,     0,  1, 0) 

# Apply transform and save 
im = im.convert("RGB", Matrix) 
im.save('result.png') 

或者,转换为Numpy数组,进行一些处理,然后转换回PIL图像:
from PIL import Image 

# Open image 
im = Image.open('image.jpg') 

# Make into Numpy array of floats
na = np.array(im).astype(np.float)

# Multiply all red values by 1.1
na[...,0] *= 1.1

# Reduce green values
na[...,1] *= 0.9

# You may want to use "np.clip()" here to ensure you don't exceed 255

# Convert Numpy array back to PIL Image and save
pi = Image.fromarray(na.astype(np.uint8))
pi.save('result.png') 

此选项的另一个好处是可以将numpy数组与 OpenCV scikit-image vips wand 和其他库进行混合和处理,以完成更复杂的几何处理,形态学处理,形态学视频处理,SIFT,对象跟踪...

关于python-imaging-library - 如何使用PIL访问和更改颜色 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320564/

相关文章:

python - PIL 中的 PNG 显示在 OS X Mavericks 上损坏了吗?

python - 在图像上绘制多个透明蒙版

opencv - 为什么用 cv2 读取图像与 PIL 有不同的行为?

python - 为什么在 for 循环中使用 PIL 的 Image.paste 时出现图像重叠问题?

python - 获取属性错误: im must have seek method while trying to save as GIF

python - 将图像旋转 90° 时,如何阻止 PIL 交换高度/宽度?

python - 在 Python 中计算 .TIF 文件中的总页数

python - 如何将字符串转换为图像?

python - 在 PIL 中保存 GIF 时透明度不一致

opencv - 从二维图像中提取视网膜区域