如何从位图图像的RGB值获取数组?

如何从位图图像的RGB值获取数组?

问题描述:

我正在运行这段代码

from PIL import Image
import numpy as np
im = Image.open("/Users/Hugo/green_leaves.jpg")
im.load()
height, widht = im.size
p = np.array([0,0,0])
for row in range(height):
     for col in range(widht):
         a = im.getpixel((row,col))
         p = np.append(a.asarray())

但是我遇到了以下错误

Traceback (most recent call last):
   File "/Users/hugo/PycharmProjects/Meteo API/image.py", line 17, in <module>
     p = np.append(a.asarray())
 AttributeError: 'tuple' object has no attribute 'asarray'

你能帮我吗?

您提到了numpy.如果您想要图像的numpy数组,请不要对其进行迭代,只需执行data = np.array(im).

You mentioned numpy. If you want a numpy array of the image, don't iterate through it, just do data = np.array(im).

例如

from PIL import Image
import numpy as np
im = Image.open("/Users/Hugo/green_leaves.jpg")
p = np.array(im)

通过反复附加一个numpy数组来构建numpy数组效率非常低. numpy数组不像python列表(python列表很好地达到了这个目的!).它们是固定大小,同构,内存有效的数组.

Building up a numpy array by repeatedly appending to it is very inefficient. Numpy arrays aren't like python lists (python lists serve that purpose very well!!). They're fixed-size, homogenous, memory-efficient arrays.

如果您确实想通过追加来构建numpy数组,请使用一个列表(可以将其有效地追加到列表中),然后将该列表转换为numpy数组.

If you did want to build up a numpy array through appending, use a list (which can be efficiently appended to) and then convert that list to a numpy array.

但是,在这种情况下,PIL图像支持直接转换为numpy数组.

However, in this case, PIL images support being converted to numpy arrays directly.

再说一遍,我上面给出的示例并非100%等价于您的代码. p将是宽度乘以numbands(3或4)阵列的高度,而不是原始示例中的numpixels by numbands阵列.

On one more note, the example I gave above isn't 100% equivalent to your code. p will be a height by width by numbands (3 or 4) array, instead of a numpixels by numbands array as it was in your original example.

如果您想将阵列整形为numband的numpixels,请执行以下操作:

If you want to reshape the array into numpixels by numbands, just do:

p = p.reshape(-1, p.shape[2])

(或等效为p.shape = -1, p.shape[2])

这将以数字带(3或4,取决于是否有alpha通道)将数组重塑为width*height数组.换句话说,图像中的红色,绿色,蓝色,alpha像素值的序列. -1是一个占位符,告诉numpy根据指定的其他尺寸为第一个轴计算合适的形状.

This will reshape the array into width*height by numbands (either 3 or 4, depending on whether or not there's an alpha channel) array. In other words a sequence of the red,green,blue,alpha pixel values in the image. The -1 is a placeholder that tells numpy to calculate the appropriate shape for the first axes based on the other sizes that are specified.