簡體   English   中英

如何使用PIL將灰度轉換為假色?

[英]How to turn grayscale into false color using PIL?

我似乎無法弄清楚如何使用我的灰度函數並將其更改為給我假顏色。 我知道我需要將每種顏色(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 種假色的相同調色板。

灰度到假彩色圖像轉換的例子

你想做這樣的事情嗎?

看起來您要做的就是確定每個像素的平均亮度,並使每個像素變灰。 我會為此使用本機 Image 功能,或者如果您想操作單個像素,至少使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM