![](/img/trans.png)
[英]Converting an RGB image to grayscale and manipulating the pixel data in python
[英]Converting a PIL image in python to grayscale pixel by pixel, leaving 1 color alone
我正在尝试在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
这不是完美的,但可行的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.