将图像转换为灰度输出错误的结果
Converting image to greyscale outputs wrong result
def desaturate_image(self, image):
desatimage = Image.new(image.mode, image.size)
pixellist = []
print(len(pixellist))
for x in range(image.size[0]):
for y in range(image.size[1]):
r, g, b = image.getpixel((x, y))
greyvalue = (r+g+b)/3
greypixel = (int(round(greyvalue)), int(round(greyvalue)), int(round(greyvalue)))
pixellist.append(greypixel)
print(pixellist)
desatimage.putdata(pixellist)
return desatimage
我正在编写一个 python 方法来将作为参数传递的图像转换为灰度。我得到的结果是不对的。这是输入和输出。哪里错了?
您首先迭代尺寸错误的像素 - 枕头图像是列优先顺序。所以你想要
...
for y in range(image.size[1]):
for x in range(image.size[0]):
...
以便您的像素列表按列存储像素。
这给你
当然,您可以更轻松地使用 .convert
method to get a greyscale representation,它使用文档中提到的转换。
image.convert('L')
正如下面提到的 abarnert,这为您提供了一个实际上处于灰度模式 ('L'
) 的图像,而不是您当前的答案,该图像将图像保持在 RGB 模式 ('RGB'
) 并具有三次重复数据.
def desaturate_image(self, image):
desatimage = Image.new(image.mode, image.size)
pixellist = []
print(len(pixellist))
for x in range(image.size[0]):
for y in range(image.size[1]):
r, g, b = image.getpixel((x, y))
greyvalue = (r+g+b)/3
greypixel = (int(round(greyvalue)), int(round(greyvalue)), int(round(greyvalue)))
pixellist.append(greypixel)
print(pixellist)
desatimage.putdata(pixellist)
return desatimage
我正在编写一个 python 方法来将作为参数传递的图像转换为灰度。我得到的结果是不对的。这是输入和输出。哪里错了?
您首先迭代尺寸错误的像素 - 枕头图像是列优先顺序。所以你想要
...
for y in range(image.size[1]):
for x in range(image.size[0]):
...
以便您的像素列表按列存储像素。
这给你
当然,您可以更轻松地使用 .convert
method to get a greyscale representation,它使用文档中提到的转换。
image.convert('L')
正如下面提到的 abarnert,这为您提供了一个实际上处于灰度模式 ('L'
) 的图像,而不是您当前的答案,该图像将图像保持在 RGB 模式 ('RGB'
) 并具有三次重复数据.