如何使用Python Imaging Library将任何图像转换为4色调色板图像?

12

我有一台支持4色图形的设备(类似于早期的CGA)。

我想使用PIL读取图片,并使用我的4色调色板(红、绿、黄、黑)进行转换,但我无法确定是否可能。我找到了一些邮件列表存档帖子,似乎表明其他人已经尝试过并失败了。

如果您能添加一个简单的Python示例,将不胜感激!

奖励分数如果您添加一些内容,将图像转换为字节字符串,其中每个字节表示4个像素的数据(每两个比特表示0到3的颜色)。


你正在尝试对图像进行量化。这里有一些相关的技巧:https://web.archive.org/web/20080825200550/http://nadiana.com/pil-tips-converting-png-gif - John Montgomery
3个回答

18

首先,你的四种颜色调色板 (黑色、绿色、红色、黄色) 没有蓝色成分。因此,除非开始时没有蓝色成分,否则你必须接受输出图像几乎无法近似于输入图像。

试试这段代码:

import Image

def estimate_color(c, bit, c_error):
    c_new= c -  c_error
    if c_new > 127:
        c_bit= bit
        c_error= 255 - c_new
    else:
        c_bit= 0
        c_error= -c_new
    return c_bit, c_error

def image2cga(im):
    "Produce a sequence of CGA pixels from image im"
    im_width= im.size[0]
    for index, (r, g, b) in enumerate(im.getdata()):
        if index % im_width == 0: # start of a line
            r_error= g_error= 0
        r_bit, r_error= estimate_color(r, 1, r_error)
        g_bit, g_error= estimate_color(g, 2, g_error)
        yield r_bit|g_bit

def cvt2cga(imgfn):
    "Convert an RGB image to (K, R, G, Y) CGA image"
    inp_im= Image.open(imgfn) # assume it's RGB
    out_im= Image.new("P", inp_im.size, None)
    out_im.putpalette( (
        0, 0, 0,
        255, 0, 0,
        0, 255, 0,
        255, 255, 0,
    ) )
    out_im.putdata(list(image2cga(inp_im)))
    return out_im

if __name__ == "__main__":
    import sys, os

    for imgfn in sys.argv[1:]:
        im= cvt2cga(imgfn)
        dirname, filename= os.path.split(imgfn)
        name, ext= os.path.splitext(filename)
        newpathname= os.path.join(dirname, "cga-%s.png" % name)
        im.save(newpathname)

这将创建一个PNG调色板图像,只设置前四个调色板条目为您的颜色。该示例图像:

变成了

使用image2cga的输出(产生0-3值的序列),并将每四个值打包到一个字节中非常简单。

如果您需要有关代码执行的帮助,请提出问题,我会解释。

编辑1:不要重复造轮子

当然,事实证明我过于热情,正如Thomas所发现的那样,Image.quantize方法可以采用调色板图像作为参数,并以比我上述的临时方法更好的结果进行量化:

def cga_quantize(image):
    pal_image= Image.new("P", (1,1))
    pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252)
    return image.convert("RGB").quantize(palette=pal_image)

编辑1,续: 像素打包成字节

以下是用于生成打包字符串的代码(每个字节4个像素)的“附加值”:

import itertools as it

# setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys
# and values [chr(0)‥chr(255)], because PIL does not yet support
# 4 colour palette images

TUPLE2CHAR= {}

# Assume (b7, b6) are pixel0, (b5, b4) are pixel1…
# Call it "big endian"

KEY_BUILDER= [
    (0, 64, 128, 192), # pixel0 value used as index
    (0, 16, 32, 48), # pixel1
    (0, 4, 8, 12), # pixel2
    (0, 1, 2, 3), # pixel3
]
# For "little endian", uncomment the following line
## KEY_BUILDER.reverse()

# python2.6 has itertools.product, but for compatibility purposes
# let's do it verbosely:
for ix0, px0 in enumerate(KEY_BUILDER[0]):
    for ix1, px1 in enumerate(KEY_BUILDER[1]):
        for ix2, px2 in enumerate(KEY_BUILDER[2]):
            for ix3, px3 in enumerate(KEY_BUILDER[3]):
                TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3)

# Another helper function, copied almost verbatim from itertools docs
def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n)

# now the functions
def seq2str(seq):
    """Takes a sequence of [0..3] values and packs them into bytes
    using two bits per value"""
    return ''.join(
        TUPLE2CHAR[four_pixel]
        for four_pixel in grouper(4, seq, 0))

# and the image related function
# Note that the following function is correct,
# but is not useful for Windows 16 colour bitmaps,
# which start at the *bottom* row…
def image2str(img):
    return seq2str(img.getdata())

7

约翰,我也找到了第一个链接,但它并没有直接帮助我解决问题。不过它确实让我更深入地了解了量化。

昨晚睡前,我想到了以下解决方法:

import sys

import PIL
import Image

PALETTE = [
    0,   0,   0,  # black,  00
    0,   255, 0,  # green,  01
    255, 0,   0,  # red,    10
    255, 255, 0,  # yellow, 11
] + [0, ] * 252 * 3

# a palette image to use for quant
pimage = Image.new("P", (1, 1), 0)
pimage.putpalette(PALETTE)

# open the source image
image = Image.open(sys.argv[1])
image = image.convert("RGB")

# quantize it using our palette image
imagep = image.quantize(palette=pimage)

# save
imagep.save('/tmp/cga.png')

TZ.TZIOY,你的解决方案似乎是基于相同原理的。赞!我应该在停止工作并等待您的回复。我的方案比较简单,但绝对没有你的逻辑更合理。PIL 的使用很繁琐。而你的解决方案可以清楚地解释要做什么。


1
import sys
import PIL
from PIL import Image

def quantizetopalette(silf, palette, dither=False):
    """Convert an RGB or L mode image to use a given P image's palette."""

    silf.load()

    # use palette from reference image
    palette.load()
    if palette.mode != "P":
        raise ValueError("bad mode for palette image")
    if silf.mode != "RGB" and silf.mode != "L":
        raise ValueError(
            "only RGB or L mode images can be quantized to a palette"
            )
    im = silf.im.convert("P", 1 if dither else 0, palette.im)
    # the 0 above means turn OFF dithering
    return silf._makeself(im)

if __name__ == "__main__":
    import sys, os

for imgfn in sys.argv[1:]:
    palettedata = [ 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 0,] 
    palimage = Image.new('P', (16, 16))
    palimage.putpalette(palettedata + [0, ] * 252 * 3)
    oldimage = Image.open(sys.argv[1])
    newimage = quantizetopalette(oldimage, palimage, dither=False)
    dirname, filename= os.path.split(imgfn)
    name, ext= os.path.splitext(filename)
    newpathname= os.path.join(dirname, "cga-%s.png" % name)
    newimage.save(newpathname)

对于那些想要纯色的人,我修改了使用PIL将图像转换为特定调色板而不使用抖动中提供的两种解决方案。尽管这个帖子很旧了,但我们中的一些人仍然需要这些信息。Kudios


欢迎来到 Stack Overflow!感谢你提供这段代码片段,它可能会为一些问题提供即时帮助。通过展示为什么这是一个好的解决方案,适当的解释将极大地提高它的教育价值,并使它对未来遇到类似但不完全相同问题的读者更加有用。请编辑您的答案以添加解释,并指出什么限制和假设适用。 - Toby Speight

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接