将 python 中的 PIL 图像逐个像素转换为灰度像素,仅保留 1 种颜色



我正在尝试在python 3.4.2中将图像转换为灰度,但我想保留所有"红色"像素

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

现在,这会将图像转换为灰度,但据我所知,它不会像我想象的那样留下任何彩色像素,任何帮助/建议/替代方法来完成我的任务将不胜感激。

谢谢

因此,如果将来有人阅读此内容,由于我的错误,我的代码无法正常工作

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

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

最新更新