简体   繁体   中英

How do I reduce the color palette of an image in Python 3?

I've seen answers for Python 2, but support for it has ended and the Image module for Python2 is incompatible with aarch64. I'm just looking to convert some images to full CGA color, without the hassle of manually editing the image.

Thanks in advance!

Edit: I think I should mention that I'm still pretty new to Python. I think I should also mention I'm trying to use colors from a typical CGA adapter.

Here's one way to do it with PIL - you may want to check I have transcribed the list of colours accurately from here ::

#!/usr/bin/env python3

from PIL import Image

# Create new 1x1 palette image
CGA = Image.new('P', (1,1))

# Make a CGA palette and push it into image
CGAcolours = [ 
   0x00, 0x00, 0x00,
   0x00, 0x00, 0xaa,
   0x00, 0xaa, 0x00,
   0x00, 0xaa, 0xaa,
   0xaa, 0x00, 0x00,
   0xaa, 0x00, 0xaa,
   0xaa, 0x55, 0x00,
   0xaa, 0xaa, 0xaa,
   0x55, 0x55, 0x55,
   0x55, 0x55, 0xff,
   0x55, 0xff, 0x55,
   0x55, 0xff, 0xff,
   0xff, 0x55, 0x55,
   0xff, 0x55, 0xff,
   0xff, 0xff, 0x55,
   0xff, 0xff, 0xff]
CGA.putpalette(CGAcolours)

# Open our image of interest
im = Image.open('swirl.jpg')

# Quantize to our lovely CGA palette, without dithering
res = im.quantize(colors=len(CGAcolours), palette=CGA, dither=Image.Dither.NONE)

res.save('result.png')

That transforms this:

在此处输入图像描述

into this:

在此处输入图像描述


Or, if you don't really want to write any Python, you can do it on the command-line with ImageMagick in a highly analogous way:

# Create 16-colour CGA swatch in file "cga16.gif"
magick xc:'#000000' xc:'#0000AA' xc:'#00AA00' xc:'#00AAAA' \
       xc:'#AA0000' xc:'#AA00AA' xc:'#AA5500' xc:'#AAAAAA' \
       xc:'#555555' xc:'#5555FF' xc:'#55FF55' xc:'#55FFFF' \
       xc:'#FF5555' xc:'#FF55FF' xc:'#FFFF55' xc:'#FFFFFF' \
       +append cga16.gif

That creates this 16x1 swatch (enlarged so you can see it):

在此处输入图像描述

# Remap colours in "swirl.jpg" to the CGA palette
magick swirl.jpg +dither -remap cga16.gif resultIM.png

在此处输入图像描述


Doubtless the code could be converted for EGA, VGA and the other early PC hardware palettes... or even to the Rubik's Cube palette:

在此处输入图像描述

Resulting in:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM