【问题标题】:"TypeError: integer argument expected, got float" in PILPIL 中的“TypeError:需要整数参数,得到浮点数”
【发布时间】:2017-02-05 02:56:13
【问题描述】:

我在这里有一个程序,我在这里遇到了一个关于堆栈溢出的问题。它应该调整图像的对比度,但我收到以下错误:

Traceback (most recent call last):
  File "<string>", line 420, in run_nodebug
  File "<module1>", line 20, in <module>
  File "<module1>", line 16, in change_contrast
  File "C:\EduPython\App\lib\site-packages\PIL\Image.py", line 1512, in putpixel
    return self.im.putpixel(xy, value)
TypeError: integer argument expected, got float

帖子太旧了,所以我认为写它的人不会看到我的请求,所以我在这里发帖。 代码如下:

from PIL import Image

def change_contrast(img, level):
    def truncate(v):
        return 0 if v < 0 else 255 if v > 255 else v


    img = Image.open("C:\\Users\\omar\\Desktop\\Site\\Images\\obama.png")
    img.load()

    factor = (259 * (level+255)) / (255 * (259-level))
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            color = img.getpixel((x, y))
            new_color = tuple(truncate(factor * (c-128) + 128) for c in color)
            img.putpixel((x, y), new_color)

    return img

result = change_contrast('test_image1.jpg', 128)
result.save('test_image1_output.jpg')
print('done')

【问题讨论】:

    标签: python python-3.x python-imaging-library


    【解决方案1】:

    嗯,truncate 是什么?

    试着在你说truncate的地方说int

    【讨论】:

    • 截断在def change_contrast(img, level) 之后的开头定义为def truncate(v)
    • factor 是一个浮点数,所以 new_color 最终是一个浮点数元组。 putpixel 想要一个整数元组。
    • 您需要确保 new_color 是整数元组,而不是浮点数元组。更改 truncate 以使其返回一个 int...或者在对 truncate() 的调用周围添加 int()。
    猜你喜欢
    • 1970-01-01
    • 2019-10-16
    • 2018-05-18
    • 2014-04-08
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多