【发布时间】:2017-09-04 19:52:16
【问题描述】:
我正在尝试在 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
现在这会将图像转换为灰度,但据我所知,它不会像我想象的那样留下任何彩色像素,任何帮助/建议/替代方法来完成我的任务将不胜感激。
谢谢
【问题讨论】:
-
我尝试遵循以下指示: 1 从文件中读取图像 2 循环并在每个像素上调用 getpixel() 以获取其颜色 3 将其 r/g/b 与您想要的颜色进行比较。如果它超出您所需颜色的某个阈值,请使用一些公式转换为灰度(例如将 rgb 设置为 3 个值的平均值)并使用 putpixel 替换该像素保存图像可能有更有效的方法,但这是获得您想要的东西的简单方法。
-
如果您想单独保留 红色 像素,您可以获取图像的 红色通道 并对其执行阈值。然后,您可以用原始图像掩盖生成的图像,以获得所有红色和接近红色的像素。我不必写这么大的代码
标签: python image-processing python-imaging-library image-manipulation