简体   繁体   中英

“TypeError: integer argument expected, got float” in PIL

I have program here that I caught on a question here on stack overflow. It's supposed to adjust the constrast of an image, but i get the following error:

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

The post is quite old so I don't think the person who wrote it would see my request, so I'm posting here. Here's the code:

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')

Hmm, what's truncate ?

Try saying int where you're saying truncate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM