在 python 中使用 PIL 时,绿色通道中的像素值不符合预期

Pixel values in green channel aren't as expected when using PIL in python

我正在尝试看看是否可以从图像中获取像素值。但是我得到的图像值并不是我期望的那样。 (具体来说,绿色三角形的绿色通道给了我一个奇怪的值)

为了解决这个问题,我进行了 运行 2 个小实验。

1) 我绘制了 2 个三角形:粉红色和红色。我得到了我期望的像素值。

2) 我绘制了 2 个三角形:粉红色和绿色。我没有得到我期望的值。

所以对于第一种情况,我事先知道,我希望得到这些像素值:

所以使用这个简单的函数,我将绘制这些三角形:

def get_pixel_vals(to_plot):
    im = Image.new("RGB", (140,125)) 

    for a_vertice in to_plot:
        ImageDraw.Draw(im).polygon(a_vertice[1], outline=a_vertice[0], fill=None)

    pix = np.array(im)
    for channel_num, color_channel in enumerate(['red', 'green', 'blue']):
        channel_list = []
        channel_array = pix[..., channel_num]  # gets you the R, G, or B channel of the numpy array
        print '********* \n', color_channel,  'channel, min:', channel_array.min()
        channel_list.append(channel_array.flatten().tolist())
        channel_flat = [item for alist in channel_list for item in alist]
        print color_channel, 'num unique values:', len(set(channel_flat))
        print color_channel, 'values:', list(set(channel_flat))
        imshow(im)

to_plot_pink_red = [ ['pink', [(25,25), (25,100), (50,100), ]] , ['red', [(100,25), (100,100), (125, 100)]] ]
get_pixel_vals(to_plot_pink_red)

然后我得到:

********* 
red channel, min: 0
red num unique values: 2
red values: [0, 255]
********* 
green channel, min: 0
green num unique values: 2
green values: [0, 192]
********* 
blue channel, min: 0
blue num unique values: 2
blue values: [0, 203]

完美!正是我所期待的!

那么如果我在绿色三角形旁边绘制一个粉色三角形呢?

我希望

我几乎明白了……但还不完全是!

to_plot_pink_green = [ ['pink', [(25,25), (25,100), (50,100), ]] , ['green', [(100,25), (100,100), (125, 100)]] ]
get_pixel_vals(to_plot_pink_green)

********* 
red channel, min: 0
red num unique values: 2
red values: [0, 255]
********* 
green channel, min: 0
green num unique values: 3
green values: [0, 192, 128]
********* 
blue channel, min: 0
blue num unique values: 2
blue values: [0, 203]

我预计 G 频道 [0, 192, 255]...但为什么我得到 [0, 192, 128]? 为什么 255 变成了 128?

您使用的颜色名称在 ImageColor.py 中定义。 "green" 映射到 "#008000",这就是您在绿色通道中只看到 128 的原因。如果您想要 rgb 值为 0、255、0,您可以使用 "lime""#00ff00"