1

我正在从这里寻找示例和问题。我创造了东西。我希望 rgb 在像素上进行十六进制。我的代码,但我没有解决,

#-*- coding: utf-8 -*-

import Image

def read(ch):
    return list(ch.getdata())

def hex2rgb(v):
    v = v.lstrip('#')
    lv = len(v)
    return tuple(int(v[i:i+lv/3], 16) for i in range(0, lv, lv/3))

def rgb2hex(rgb):
    return '#%02x%02x%02x' % rgb

imj = Image.open('sample.png','r')
x,y = imj.size
pix = list(imj.getdata())

if imj.mode in ('RGBA','LA') or (imj.mode == 'P' and 'transparency' in imj.info):   
    red,green,blue,alfa = imj.convert('RGBA').split()
    #rgb = imj.convert('RGBA').split()[:-1]

    r,g,b,a = read(red),read(green),read(blue),read(alfa)

for r_,g_,b_ in r,g,b:
    print rgb2hex((r_,g_,b_))

r,g,b 中的 r_,g_,b_ 出现错误:但我如何解决不知道?

谢谢你的兴趣?干得好..

4

1 回答 1

8

问题:

for r_,g_,b_ in r,g,b:

修复:

for r_, g_, b_ in zip(r, g, b):

但老实说,你让事情变得不必要地复杂化了:

#!/usr/bin/python
from PIL import Image

def rgb2hex(r, g, b):
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)

img = Image.open('sample.png')

if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):   
    pixels = list(img.convert('RGBA').getdata())

    for r, g, b, a in pixels: # just ignore the alpha channel
       print rgb2hex(r, g, b)

更新:除了十六进制颜色之外,还获取像素的 x 和 y 位置

#!/usr/bin/python
from PIL import Image

def rgb2hex(r, g, b):
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)

img = Image.open('sample.png')

if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):   
    pixels = img.convert('RGBA').load()
    width, height = img.size

    for x in range(width):
        for y in range(height):
            r, g, b, a = pixels[x, y]
            print 'x = %s, y = %s, hex = %s' % (x, y, rgb2hex(r, g, b))
于 2013-11-11T22:45:42.347 回答