【发布时间】:2016-05-10 15:29:32
【问题描述】:
我想将多个图像的像素亮度值存储在一个 3D 数组中,但我不确定如何一次性设置 3D“立方体”的整个“平面”的值。这是我的尝试:
imag = Image.open(imagArray[i])
imagPix[:,:,i] = self.getPixelValues(imag)
imagArray 是存储在本地计算机上的图像的文件路径数组,imagPix 是像素值的 3D 数组。 imagPix 最初定义为:
imagPix = np.zeros((width, height, lenImagArray))
其中 width 和 height 是图像的尺寸,lenImagArray 是要保存在数组中的图像数(在本例中为 3)。我已经尝试使用 '0:' 和 ':' 运算符的 imagPix[:,:,i] 行无济于事。
我收到的具体错误是:
ValueError: could not broadcast input array from shape (640, 480, 3) into shape (640, 480)
getPixelValues 方法返回像素亮度值的二维数组。代码如下:
def getPixelValues(self, pixImg): ## pixImg is the location of the image, not the image itself
## open image and convert to rgb
imag = Image.open(str(pixImg))
imag = imag.convert('RGB')
## get size of image
width, height = imag.size
pixData = list(imag.getdata())
pixData = [pixData[i * width:(i+1) * width] for i in xrange(height)]
## close image and return pixel array
imag.close()
return pixData
我是否必须使用 for 循环而不是一次性设置所有值? 提前致谢。 :)
编辑:
现在我的 getdata() 返回元组的问题已经解决,我在使用 numpy.mean() 时遇到了一个新问题:
pixData = np.array(imag.getdata())
pixData = [pixData[i * width:(i+1) * width] for i in xrange(height)]
pixData = np.mean(pixData, 2)
这给了我错误:
ValueError: 无法将输入数组从形状 (480, 640) 广播到形状 (640, 480)
所以我的数组的尺寸已经无缘无故地“旋转”了。
【问题讨论】:
-
在您执行此操作之前,
imagPix中有什么内容? -
抱歉,这是一个 3D 零数组。我将使用适当的代码更新帖子。
-
它的前两个尺寸是否与您的图像尺寸相同?并且:当您尝试这样做时,实际出了什么问题? (你收到错误消息吗?什么也没发生?数据损坏?愤怒的猴子从你的电脑屏幕上飞出来攻击你?)
-
是的,前两个维度和图片一样。哦,是的,抱歉,我已更新代码以包含错误消息。
-
哦,我想这是因为 imag.getdata() 返回每个像素的 RGB 值,因此是 3D 数组而不是 2D 数组。