我正在寻找这里的例子和问题。我创造了一些东西我希望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_:但我怎么解决都不知道?
感谢您的兴趣? 好作品..
答案 0 :(得分:3)
问题:
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))