我似乎无法弄清楚如何使用我的灰度函数并将其更改为给我假颜色。我知道我需要将每种颜色(R、G、B)分成多个范围,然后根据每种颜色的范围分配颜色。有谁知道这是如何工作的?
def grayscale(pic):
(width,height) = pic.size
for y in range (height):
for x in range(width):
pix = cp.getpixel((x,y))
(r, g, b) = pix
avg = (r + g + b)//3
newPix = (avg, avg, avg)
cp.putpixel((x,y),newPix)
return cp
最佳答案
由于您从未在评论中回答我的最后一个后续问题,因此我做了一些猜测并实现了一些东西来说明如何仅使用 PIL
(或 pillow
)模块来完成它。
简而言之,代码将图像转换为灰度,将生成的 0% 到 100% 亮度(强度)像素范围划分为大小相等的子范围,然后从调色板中为每个子范围分配一种颜色。
from PIL import Image
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale
try:
xrange
except NameError: # Python 3.
xrange = range
def falsecolor(src, colors):
if Image.isStringType(src): # File path?
src = Image.open(src)
if src.mode not in ['L', 'RGB', 'RGBA']:
raise TypeError('Unsupported source image mode: {}'.format(src.mode))
src.load()
# Create look-up-tables (luts) to map luminosity ranges to components
# of the colors given in the color palette.
num_colors = len(colors)
palette = [colors[int(i/256.*num_colors)] for i in xrange(256)]
luts = (tuple(c[0] for c in palette) +
tuple(c[1] for c in palette) +
tuple(c[2] for c in palette))
# Create grayscale version of image of necessary.
l = src if Image.getmodebands(src.mode) == 1 else grayscale(src)
# Convert grayscale to an equivalent RGB mode image.
if Image.getmodebands(src.mode) < 4: # Non-alpha image?
merge_args = ('RGB', (l, l, l)) # RGB version of grayscale.
else: # Include copy of src image's alpha layer.
a = Image.new('L', src.size)
a.putdata(src.getdata(3))
luts += tuple(xrange(256)) # Add a 1:1 mapping for alpha values.
merge_args = ('RGBA', (l, l, l, a)) # RGBA version of grayscale.
# Merge all the grayscale bands back together and apply the luts to it.
return Image.merge(*merge_args).point(luts)
if __name__ == '__main__':
R, G, B = (255, 0, 0), ( 0, 255, 0), ( 0, 0, 255)
C, M, Y = ( 0, 255, 255), (255, 0, 255), (255, 255, 0)
filename = 'test_image.png'
# Convert image into falsecolor one with 4 colors and display it.
falsecolor(filename, [B, R, G, Y]).show()
下面是一张合成图,显示了一张 RGB 测试图像、中间的内部 256 级灰度图像,以及将其更改为仅包含四种颜色(每种颜色代表 64 级强度范围)的假彩色的最终结果:这是另一个合成图,只是这次显示了将已经灰度化的图像转换为 4 种假色的相同调色板。
你想做这样的事情吗?
关于python - 如何使用PIL将灰度转换为假色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31507479/