0

http://pastebin.com/v0B3Vje2 我正在寻找一种从图像中获取像素的方法,然后在另一个程序中找到最接近的颜色(我可以将它编译到“另一个程序”的源代码中;如果无需源注入即可兼容),然后使用该颜色并将其放置在正确的像素上。基本上,Script/Code/Executable 以图像文件为例,然后用最接近的匹配重新创建每个像素。我正在谈论的节目是The Powder Toy。(powdertoy.co.uk)。如果您知道,我将它用于私人目的和概念验证,因为“公共保存”中不能包含 CGI。那里的用户之一 JoJoBond 被允许这样做,因为他/她首先这样做了。

4

2 回答 2

1

您可以使用Python Imaging Library加载图像并提取像素颜色值:

import Image

img = Image.open('random.png')
width, height = img.size
pixels = img.getdata()
print 'pixels:'
for i, px in enumerate(img.getdata()):

    # decide whether to replace this pixel

    # call out to external program to translate color value
    r, g, b = px
    npx = (b, g, r)

    # replace pixel with new color value        
    y = i / width
    x = i % width
    img.putpixel((x, y), npx)

    print px, npx

输出:

pixels:
(58, 0, 0) (0, 0, 58)
(0, 0, 0) (0, 0, 0)
(0, 0, 4) (4, 0, 0)
(0, 0, 0) (0, 0, 0)
(0, 0, 0) (0, 0, 0)
(0, 245, 0) (0, 245, 0)
(0, 0, 0) (0, 0, 0)
(0, 0, 0) (0, 0, 0)
(14, 0, 0) (0, 0, 14)
...
于 2011-04-28T14:08:57.540 回答
1

也许使用scipy.cluster.vq.vq来量化图像:

import numpy as np
import scipy.cluster.vq as vq
import Image
import random

img = Image.open('cartoon.png').convert('RGB')
arr = np.asarray(img)
shape_orig = arr.shape

# make arr a 2D array
arr = arr.reshape(-1,3)

# create an array of all the colors in the image
palette=np.unique(arr.ravel().view([('r',np.uint8),('g',np.uint8),('b',np.uint8)]))
# randomly select 50 colors from the palette
palette=palette[random.sample(range(len(palette)),50)]

# make palette a 2D array
palette=palette.view('uint8').reshape(-1,3)

# Quantize arr to the closet color in palette
code,dist=vq.vq(arr,palette)
arr_quantized=palette[code]

# make arr_quantized have the same shape as arr
arr_quantized=arr_quantized.reshape(shape_orig)
img_new=Image.fromarray(arr_quantized)
img_new.save('/tmp/cartoon_quantized.png')

与卡通.png:

在此处输入图像描述

上面的代码产生了cartoon_quantized.png:

在此处输入图像描述

注意:我并不精通定义接近颜色的最佳方法是什么。

上面的代码用于vq.vq在调色板中选择与给定图像中的颜色具有最小欧几里德距离的颜色。我不确定——事实上我怀疑——使用欧几里得距离和 RGB 元组是定义接近颜色的最佳方法。

您可能希望选择与 RGB 不同的颜色系统,甚至可能选择与欧几里得距离不同的度量标准。vq.vq不幸的是,如果您需要与欧几里德距离不同的度量,我不确定是否可以使用...

于 2011-04-28T15:52:36.413 回答