Skip to content

Instantly share code, notes, and snippets.

Created May 22, 2024 08:16
Show Gist options
  • Save gledos/71414747e12b2077569e42bf93f152ad to your computer and use it in GitHub Desktop.
Save gledos/71414747e12b2077569e42bf93f152ad to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
This script is from Astropulse, Written by ChatGPT-4o into a ready-to-use script version.
该脚本,来自 Astropulse,经过 ChatGPT-4o 编写为了可直接使用的脚本版本。
Usage: python path/to/pixle/art.png
import sys
import numpy as np
from PIL import Image
from sklearn.cluster import KMeans
import os
def extract_palette(image, num_colors):
# 将图像转换为 RGB
image = image.convert('RGB')
# 获取图像像素数据
pixels = np.array(image)
pixels = pixels.reshape((-1, 3))
# 使用 k-means 聚类算法提取调色板
kmeans = KMeans(n_clusters=num_colors, random_state=0).fit(pixels)
palette = kmeans.cluster_centers_.astype(int)
return palette
def save_palette(palette, file_path):
# 保存调色板为 .gpl 文件
with open(file_path, 'w') as f:
f.write("GIMP Palette\n")
f.write("Name: Palette\n")
f.write("Columns: 16\n")
for color in palette:
f.write(f"{color[0]} {color[1]} {color[2]} Untitled\n")
def quantize_image(image, palette):
# 将调色板应用于图像
palette_image ='P', (1, len(palette)))
image = image.convert('RGB').quantize(palette=palette_image, dither=Image.NONE)
return image.convert('RGB')
def main(input_path):
# 打开图像
image =
# 提取调色板
num_colors = 256 # 最大颜色数量,可以根据需要调整
palette = extract_palette(image, num_colors)
# 保存调色板
palette_path = os.path.splitext(input_path)[0] + '.gpl'
save_palette(palette, palette_path)
# 量化图像
quantized_image = quantize_image(image, palette)
# 保存量化后的图像
output_path = os.path.splitext(input_path)[0] + '_sd-palettize.png'
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: python [file-name]")
input_path = sys.argv[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment