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 

它并不完美,但它是一个可行的解决方案

相关问题