Python PIL中是否有一个Image.point()方法允许您同时对所有三个通道进行操作?
我想为每个像素编写一个基于红色、绿色和蓝色通道的点过滤器,但这似乎不符合Python PIL中是否有一个Image.point()方法允许您同时对所有三个通道进行操作?,python,python-imaging-library,Python,Python Imaging Library,我想为每个像素编写一个基于红色、绿色和蓝色通道的点过滤器,但这似乎不符合point()的功能--它似乎一次在单个通道中的单个像素上运行。我想这样做: def colorswap(pixel): """Shifts the channels of the image.""" return (pixel[1], pixel[2], pixel[0]) image.point(colorswap) 有没有一种等效的方法可以让我使用一个过滤器,它接收RGB值的三元组并输出一个新的三元组
point()
的功能--它似乎一次在单个通道中的单个像素上运行。我想这样做:
def colorswap(pixel):
"""Shifts the channels of the image."""
return (pixel[1], pixel[2], pixel[0])
image.point(colorswap)
有没有一种等效的方法可以让我使用一个过滤器,它接收RGB值的三元组并输出一个新的三元组 根据到目前为止的回复,我猜答案是“不” 但你可以雇佣numpy来高效地完成这类工作:
def colorswap(pixel):
"""Shifts the channels of the image."""
return (pixel[1], pixel[2], pixel[0])
def npoint(img, func):
import numpy as np
a = np.asarray(img).copy()
r = a[:,:,0]
g = a[:,:,1]
b = a[:,:,2]
r[:],g[:],b[:] = func((r,g,b))
return Image.fromarray(a,img.mode)
img = Image.open('test.png')
img2 = npoint(img, colorswap)
img2.save('test2.png')
额外好处:看起来图像类不是只读的,这意味着您可以让新的
npoint
函数感觉更像点
(除非让人困惑,否则不推荐):
您可以使用
load
方法快速访问所有像素
def colorswap(pixel):
"""Shifts the channels of the image."""
return (pixel[1], pixel[2], pixel[0])
def applyfilter(image, func):
""" Applies a function to each pixel of an image."""
width,height = im.size
pixel = image.load()
for y in range(0, height):
for x in range(0, width):
pixel[x,y] = func(pixel[x,y])
applyfilter(image, colorswap)
image.load()
方法正是我想要的。非常感谢。
def colorswap(pixel):
"""Shifts the channels of the image."""
return (pixel[1], pixel[2], pixel[0])
def applyfilter(image, func):
""" Applies a function to each pixel of an image."""
width,height = im.size
pixel = image.load()
for y in range(0, height):
for x in range(0, width):
pixel[x,y] = func(pixel[x,y])
applyfilter(image, colorswap)