从无色图片数据(PIL)中抓取RGB值

时间:2014-11-12 16:42:37

标签: python python-imaging-library

如果它是无色的,我需要知道是否可以从它的(获取)数据中获取图像RGB值。我目前有一段看起来像这样的代码(np = numpy):

Image image = Image.open(path)
n, m = image.size
data = np.array(image.getdata())
R = np.zeros(n*m, dtype=np.float)
G = np.zeros(n*m, dtype=np.float)
B = np.zeros(n*m, dtype=np.float)

for x in range (0, n*m):
    RGB = data[x]
    R[x] = RGB[0]
    G[x] = RGB[1]
    B[x] = RGB[2]

这让我抓住所有的RGB值。它与彩色图片完美配合,但黑白图片在尝试设置R [x]时崩溃。错误:

indexError: invalid index to scalar variable

此行引发此错误

R[x] = RGB[0]

1 个答案:

答案 0 :(得分:1)

您可以使用:

img = Image.open(path)
layeredimg = img.convert('RGB')

在转换为numpy数组之前执行此操作。您可以找到更多信息the docs for PIL.Image(严格来说,Pillow是PIL的一个分支)。

如果你想在条件下这样做(即如果你想对黑白和彩色图像使用相同的代码)你可以这样做:

img = Image.open(path)
if img.layers == 1:
    img = img.convert('RGB')
相关问题