【问题标题】:How to turn grayscale into false color using PIL?如何使用 PIL 将灰度变为假色?
【发布时间】:2015-10-09 01:02:31
【问题描述】:

我似乎无法弄清楚如何获取灰度函数并将其更改为给我假颜色。我知道我需要将每种颜色(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

【问题讨论】:

  • 什么是cp?最后你想要什么样的效果——你能举个例子吗? thisthis 是否相关/有用(即使不是 Python)?
  • 听起来您真正想做的是将彩色图像转换为假彩色图像(这涉及到找到每个像素原始颜色的三个分量的平均值)。你想用什么假配色方案?描述 rgb -> rgb 颜色的映射。
  • 听起来您想为图像的每个独特强度赋予独特的颜色。您实际上在做的只是计算每个 RGB 像素的粗略亮度,这不是正确的方法。此外,您在问题陈述中描述的是均匀量化,它将具有全调色板的图像转换为较小的图像。您的问题标题和问题陈述有冲突...考虑编辑以确保一致性。
  • 我很抱歉这是我第一次使用这个网站。 Cp = "图像".copy()。我需要做的是在 255 个中,我需要将其分成块并为每个块(例如:0-31 = 红色)分配一个配色方案。因此,该范围内的像素将变为该颜色。
  • 好的,这是一个更好的描述。会有多少块/颜色以及它们将如何指定?

标签: python image-processing colors python-imaging-library grayscale


【解决方案1】:

由于您从未在 cmets 中回答我最后的后续问题,因此我做了一些猜测并实现了一些东西来说明如何仅使用 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 种假色调色板。

你想做这样的事情吗?

【讨论】:

    【解决方案2】:

    看起来您要做的就是确定每个像素的平均亮度,并将每个像素设为灰色。我会为此使用本机图像功能,或者如果您想操作单个像素,至少使用numpy 而不是嵌套的for 循环。示例:

    from PIL import Image, ImageDraw
    import numpy as np
    
    def makeGrey():
        W = 800
        H = 600
        img = Image.new('RGB', (W, H))
        draw = ImageDraw.Draw(img)
    
        draw.rectangle((0, H * 0 / 3, W, H * 1 / 3), fill=(174, 28, 40), outline=None)
        draw.rectangle((0, H * 1 / 3, W, H * 2 / 3), fill=(255, 255, 255), outline=None)
        draw.rectangle((0, H * 2 / 3, W, H * 3 / 3), fill=(33, 70, 139), outline=None)
    
        img.show()
    
        pixels = np.array(img.getdata())
        avg_pixels = np.sum(pixels, axis=1) / 3
        grey_img = avg_pixels.reshape([H, W])
    
        img2 = Image.fromarray(grey_img)
        img2.show()
    
    if __name__ == '__main__':
        makeGrey()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2017-07-21
      • 1970-01-01
      • 2017-03-08
      • 2023-03-24
      相关资源
      最近更新 更多