Python 如何使用PIL将灰度转换为假彩色?

Python 如何使用PIL将灰度转换为假彩色?,python,image-processing,colors,python-imaging-library,grayscale,Python,Image Processing,Colors,Python Imaging Library,Grayscale,我似乎不知道如何使用我的灰度函数,并将其更改为假颜色。我知道我需要将每种颜色(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)

我似乎不知道如何使用我的灰度函数,并将其更改为假颜色。我知道我需要将每种颜色(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

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

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()

由于您在评论中没有回答我的最后一个后续问题,我做了一些猜测,并实现了一些东西来说明如何仅使用
PIL
(or)模块来实现

简而言之,代码将图像转换为灰度,将得到的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()
从PIL导入图像
从PIL.ImageColor导入getcolor、getrgb
从PIL.ImageOps导入灰度
尝试:
润智
除了名称错误:#Python 3。
xrange=范围
def falsecolor(src,颜色):
if Image.isStringType(src):#文件路径?
src=Image.open(src)
如果src.mode不在['L','RGB','RGBA']中:
raise TypeError('不支持的源映像模式:{}'。格式(src.mode))
src.load()
#创建查找表(LUT)以将亮度范围映射到组件
#调色板中给定的颜色。
num_colors=len(颜色)
调色板=[colors[int(i/256.*num_colors)],用于X范围内的i(256)]
luts=(元组(调色板中c的c[0])+
元组(c[1]表示调色板中的c)+
元组(c[2]表示调色板中的c))
#根据需要创建图像的灰度版本。
l=src if Image.getmodebands(src.mode)==1 else灰度(src)
#将灰度转换为等效的RGB模式图像。
如果Image.getmodebands(src.mode)<4:#非alpha图像?
合并参数=('RGB',(l,l,l))#RGB版本的灰度。
其他:#包括src图像的alpha层副本。
a=图像。新建('L',src.size)
a、 putdata(src.getdata(3))
luts+=tuple(xrange(256))#为alpha值添加1:1映射。
合并参数=('RGBA',(l,l,l,a))#灰度的RGBA版本。
#将所有灰度带合并在一起,并对其应用LUT。
返回Image.merge(*merge_args).point(luts)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
R、 G,B=(255,0,0),(0255,0),(0,0255)
C、 M,Y=(0,255,255),(255,0,255),(255,255,0)
文件名='test_image.png'
#将图像转换为具有4种颜色的假彩色图像并显示。
falsecolor(文件名[B,R,G,Y]).show()
下面是显示RGB测试图像、中间内部256级灰度图像以及将其更改为仅由四种颜色(每种颜色表示64级强度范围)组成的假彩色图像的合成图:

这是另一个合成图,只是这一次显示了将一个已经灰度化的图像转换为4种假颜色的同一调色板


像这样的事情是你想要做的吗?

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