0

我試圖將圖像轉換在Python 3.4.2灰度,但我想給所有的「紅」像素單獨在Python由像素灰度像素轉換一個PIL形象,留下獨自1種顏色

from numpy import * 
from pylab import * 
from PIL import Image 
from PIL import ImageOps 


def grayscale(picture): 
    res = Image.new(picture.mode, picture.size) 
    red = '150,45,45'     # for now I'm just tyring 
    x = red.split(",")     # to change pixels with R value less than 150 
             #and G/B values greater than 45 
    width, height = picture.size   #to greyscale 

    for i in range(0, width): 
     for j in range(0, height): 
      pixel = picture.getpixel((i, j)) #get a pixel 
      pixelStr = str(pixel) 
      pixelStr = pixelStr.replace('(', '').replace(')', '') 
      pixelStr.split(",")     #remove parentheses and split so we 
               #can convert the pixel into 3 integers 


      #if its not specifically in the range of values we're trying to convert 
      #we place the original pixel otherwise we convert the pixel to grayscale 

      if not (int(pixelStr[0]) >= int(x[0]) and int(pixelStr[1]) <= int(x[1]) and int(pixelStr[2]) <= int(x[2])): 
       avg = (pixel[0] + pixel[1] + pixel[2])/3 
       res.putpixel((i, j), (int(avg), int(avg), int(avg))) 
      else: 
       res.putpixel(pixel) 
return res 

現在,這將圖像轉換爲灰度,但據我所知,它不會留下像我想的那樣的任何彩色像素,任何幫助/建議/替代方式來完成我的任務將不勝感激。

謝謝

+0

我試圖按照這些方向:從文件 1讀取圖像循環並調用每個像素上的getpixel()以獲取其顏色 3將其r/g/b與您想要的顏色進行比較。如果它落在你想要的顏色的某個 閾值之外,則使用一些公式轉換爲 灰度(例如,將rgb設置爲3個值的平均值),並使用putpixel替換該像素 保存圖像 可能效率更高方式,但這是一個簡單的方法來獲得你想要的。 –

+0

如果你想單獨留下**紅色**像素,你可能已經獲得了圖像的**紅色通道**並對此執行了閾值。然後你可以用你的原稿遮蓋得到的圖像,以獲得全部紅色並接近紅色像素。我不必寫這麼大的代碼 –

回答

0

所以櫃面任何人在將來我的代碼不能正常工作,由於我的部分錯誤

res.putpixel(pixel) 

應該已經拋出一個錯誤讀這一點,因爲我沒有得到它只是將像素置於顏色信息的位置。既然它沒有拋出一個錯誤,我們從來沒有真正進入我的else語句中。

要求幫助隊友,我們改變了我的代碼如下:

from numpy import * 
from PIL import Image 

red_lower_threshold = 150 
green_blue_diff_threshold = 50 
def grayscale(picture): 
    res = Image.new(picture.mode, picture.size) 

    for i in range(0, picture.size[0]): 
     for j in range(0, picture.size[1]): 
      pixel = picture.getpixel((i, j)) #get a pixel 
      red = pixel[0] 
      green = pixel[1] 
      blue = pixel[2] 

      if (red > red_lower_threshold and abs(green - blue) < green_blue_diff_threshold): 
       res.putpixel((i, j), pixel) 
      else: 
       avg = (pixel[0] + pixel[1] + pixel[2])/3 
       res.putpixel((i, j), (int(avg), int(avg), int(avg))) 

res.save('output.jpg') 
return res 

它並不完美,但它是一個可行的解決方案

相關問題