2017-03-01 93 views
0

我試圖將RGB圖片轉換爲灰度。我不想使用image.convert('L')。這只是顯示原始圖像而不更改任何內容。我曾嘗試在「紅色,綠色,藍色= 0,0,0」行中放入不同的數字,這會改變圖像的顏色,但這不是我想要的。在Python中使用PIL將像素更改爲灰度

import PIL 
    from PIL import Image 

    def grayscale(picture): 
     res=PIL.Image.new(picture.mode, picture.size) 
     width, height = picture.size 

     for i in range(0, width): 
      for j in range(0, height): 
       red, green, blue = 0,0,0 
       pixel=picture.getpixel((i,j)) 

       red=red+pixel[0] 
       green=green+pixel[1] 
       blue=blue+pixel[2] 
       avg=(pixel[0]+pixel[1]+pixel[2])/3 
       res.putpixel((i,j),(red,green,blue)) 

     res.show() 
    grayscale(Image.show('flower.jpg')) 

回答

1
import PIL 
from PIL import Image 

def grayscale(picture): 
    res=PIL.Image.new(picture.mode, picture.size) 
    width, height = picture.size 

    for i in range(0, width): 
     for j in range(0, height): 
      pixel=picture.getpixel((i,j)) 
      avg=(pixel[0]+pixel[1]+pixel[2])/3 
      res.putpixel((i,j),(avg,avg,avg)) 
    res.show() 

image_fp = r'C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg' 
im = Image.open(image_fp) 
grayscale(im) 
1

你正在做的錯誤是你不與灰度值更新像素值。通過平均R,G,B值來計算灰度。

你可以用這個代替灰度功能:

def grayscale(picture): 
    res=PIL.Image.new(picture.mode, picture.size) 
    width, height = picture.size 
    for i in range(0, width): 
      for j in range(0, height): 
       pixel=picture.getpixel((i,j)) 
       red= pixel[0] 
       green= pixel[1] 
       blue= pixel[2] 
       gray = (red + green + blue)/3 
       res.putpixel((i,j),(gray,gray,gray)) 
    res.show() 
相關問題