2017-03-01 7 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() 
関連する問題