简体   繁体   中英

Numpy flatten RGB image array

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

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)

Now if I do:

pixels = x_data.flatten()
print pixels.shape

I get: (12288000,)

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

How can I achieve that?

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

  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

Try this:

d1, d2, d3, d4 = x_data.shape

then using 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 -1 from original length and defined dimension d1 )

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)])

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_flatten = X.reshape(X.shape[0], -1).T

假设你有一个数组image_array你可以使用reshape()方法。

image_array = image_array.reshape(1000, 12288)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM