![](/img/trans.png)
[英]How to reduce the palette of PNG image in Python/Pillow to the colors being really used?
[英]How do I reduce the color palette of an image in Python 3?
我已經看到了 Python 2 的答案,但是對它的支持已經結束,並且 Python2 的 Image 模塊與 aarch64 不兼容。 我只是想將一些圖像轉換為完整的 CGA 顏色,而無需手動編輯圖像。
提前致謝!
編輯:我想我應該提到我對 Python 還是很陌生。 我想我還應該提到我正在嘗試使用來自典型CGA適配器的顏色。
這是使用 PIL 的一種方法-您可能想檢查我是否已從此處准確轉錄顏色列表::
#!/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')
這改變了這一點:
進入這個:
或者,如果您真的不想編寫任何 Python,您可以使用ImageMagick在命令行上以高度相似的方式進行:
# 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
這將創建這個 16x1 樣本(放大以便您可以看到它):
# Remap colours in "swirl.jpg" to the CGA palette
magick swirl.jpg +dither -remap cga16.gif resultIM.png
毫無疑問,代碼可以轉換為 EGA、VGA 和其他早期 PC 硬件調色板……甚至是魔方調色板:
導致:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.