How do I convert any image to a 4-color paletted image using the Python Imaging Library?

前端 未结 3 1078
谎友^
谎友^ 2020-12-08 03:19

I have a device that supports 4-color graphics (much like CGA in the old days).

I wanted to use PIL to read the image and convert it using my 4-color palette (of red

3条回答
  •  长情又很酷
    2020-12-08 04:07

    John, I found that first link as well, but it didn't directly help me with the problem. It did make me look deeper into quantize though.

    I came up with this yesterday before going to bed:

    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, your solution seems to work along the same principles. Kudos, I should have stopped working on it and waited for your reply. Mine is a bit simpler, although definately not more logical than yours. PIL is cumbersome to use. Yours explains what's going on to do it.

提交回复
热议问题