Python 类型错误:应为整数参数,将图像转换为灰度时得到浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29568598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:44:06  来源:igfitidea点击:

TypeError: integer argument expected, got float when converting an image to greyscale

pythonpython-imaging-library

提问by u4774924

I am using the following code to convert a color image to a grayscale image. Why does it throw a TypeError?

我正在使用以下代码将彩色图像转换为灰度图像。为什么会抛出一个TypeError

#!/usr/bin/python
from PIL import Image
im = Image.open("Penguins.jpg")
pixel = im.load()
width, height = im.size
for x in range(width):
    for y in range(height):
        R,G,B = pixel[x,y]
        pixel[x,y] = ((0.299*R+0.587*G+0.114*B),(0.299*R+0.587*G+0.114*B),(0.299*R+0.587*G+0.114*B))

im.save("Penguins_new.jpg")

采纳答案by Zizouz212

The argument that you are passing to pixel[x, y]needs to be an int, not a float. Try casting it as an integer.

您传递给的参数pixel[x, y]必须是int,而不是float。尝试将其转换为整数。

pixel[x, y] = ((int(0.299*R) + int(...