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
现在,这将图像转换为灰度,但据我所知,它不会留下像我想的那样的任何彩色像素,任何帮助/建议/替代方式来完成我的任务将不胜感激。
谢谢
我试图按照这些方向:从文件 1读取图像循环并调用每个像素上的getpixel()以获取其颜色 3将其r/g/b与您想要的颜色进行比较。如果它落在你想要的颜色的某个 阈值之外,则使用一些公式转换为 灰度(例如,将rgb设置为3个值的平均值),并使用putpixel替换该像素 保存图像 可能效率更高方式,但这是一个简单的方法来获得你想要的。 –
如果你想单独留下**红色**像素,你可能已经获得了图像的**红色通道**并对此执行了阈值。然后你可以用你的原稿遮盖得到的图像,以获得全部红色并接近红色像素。我不必写这么大的代码 –