Python Numpy 展平 RGB 图像阵列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36967920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:37:21  来源:igfitidea点击:

Numpy flatten RGB image array

pythonarraysnumpyimage-processing

提问by apples-oranges

I have 1,000 RGB images (64X64) which I want to convert to an (m, n) array.

我有 1,000 张 RGB 图像 (64X64),我想将其转换为 (m, n) 数组。

I use this:

我用这个:

import numpy as np
from skdata.mnist.views import OfficialImageClassification
from matplotlib import pyplot as plt
from PIL import Image                                                            
import glob
import cv2

x_data = np.array( [np.array(cv2.imread(imagePath[i])) for i in range(len(imagePath))] )
print x_data.shape

Which gives me: (1000, 64, 64, 3)

这给了我: (1000, 64, 64, 3)

Now if I do:

现在,如果我这样做:

pixels = x_data.flatten()
print pixels.shape

I get: (12288000,)

我得到: (12288000,)

However, I require an array with these dimensions: (1000, 12288)

但是,我需要一个具有以下维度的数组: (1000, 12288)

How can I achieve that?

我怎样才能做到这一点?

采纳答案by Ray

Apply the numpy method reshape()after applying flatten()to the flattened array:

应用到扁平化数组reshape()后应用numpy 方法flatten()

  x_data = np.array( [np.array(cv2.imread(imagePath[i])) for i in range(len(imagePath))] )

  pixels = x_data.flatten().reshape(1000, 12288)
  print pixels.shape

回答by lskrinjar

Try this:

尝试这个:

d1, d2, d3, d4 = x_data.shape

then using numpy.reshape()

然后使用 numpy.reshape()

x_data_reshaped = x_data.reshape((d1, d2*d3*d4))

or

或者

x_data_reshaped = x_data.reshape((d1, -1))

(Numpy infers the the value instead of -1from original length and defined dimension d1)

(Numpy 推断值而不是-1从原始长度和定义的尺寸d1

回答by James Evans

You can iterate over your images array and flatten each row independently.

您可以遍历图像数组并独立展平每一行。

numImages = x_data.shape[0]
flattened = np.array([x_data[i].flatten() for i in range(0,numImages)])

回答by Limkin

You could also use this: X is your 2D picture with size 32x32 for example and the -1 it simply means that it is an unknown dimension and we want numpy to figure it out. And numpy will figure this by looking at the 'length of the array and remaining dimensions' and making sure it satisfies the above mentioned criteria (What does -1 mean in numpy reshape?). T means to invert the transposition of tensors when using the axes keyword argument (https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html).

你也可以使用这个:X 是你的 2D 图片,例如大小为 32x32 和 -1 它只是意味着它是一个未知的维度,我们希望 numpy 弄清楚它。并且 numpy 将通过查看“数组的长度和剩余维度”并确保它满足上述标准(numpy reshape 中 -1 是什么意思?)来计算这一点。T 表示在使用轴关键字参数 ( https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html)时反转张量的转置。

X_flatten = X.reshape(X.shape[0], -1).T