2017-02-04 53 views
0

我有程序在這裏,我抓住了一個問題在這裏堆棧溢出。它應該調整圖像的constrast,但我得到了以下錯誤:「TypeError:整數參數預期,得到浮動」在PIL

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

回答

1

嗯,什麼是truncate

試着說int你在說什麼truncate

+0

truncate在'def change_contrast(img,level)'後面的開始被定義爲'def truncate(v)' –

+0

因子是一個浮點數,所以new_color是一個浮點數元組。 putpixel想要一個int的元組。 –

+0

您需要確保new_color是一個整數的元組,而不是一個浮點數的元組。更改截斷以使其返回一個int ...或者在調用truncate()時添加int()。 –

相關問題