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

2024-10-04 05:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python3.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

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

谢谢你


Tags: andthetoinfromimportforres
1条回答
网友
1楼 · 发布于 2024-10-04 05:34:26

因此,如果将来有人读到这篇文章,我的代码由于我的错误而无法工作

res.putpixel(pixel) 

应该是抛出一个错误,因为我没有得到一个位置来放置像素只是颜色信息。因为它没有抛出错误,所以我们实际上从未进入过我的else:statement。在

向队友寻求帮助,我们将代码改为:

^{pr2}$

这并不完美,但却是可行的解决办法

相关问题 更多 >