valueerror:无法将大小为315的数组重塑为形状(32,32)

时间:2019-03-04 19:07:31

标签: python numpy opencv

我正在尝试使用此页中的代码:https://medium.com/@muskulpesent/create-numpy-array-of-images-fecb4e514c4b

import cv2
import glob
import numpy as np

#Train data
train = []
train_labels = []
files = glob.glob (r"C:\Users\Downloads\All_Codes\image\0\*.png") # your image path
for myFile in files:
    image = cv2.imread (myFile ,cv2.IMREAD_GRAYSCALE)
    input_img_resize=cv2.resize(image,(64,64))
    train.append (input_img_resize)
    train_labels.append([0])

print(train) 
print(len(train))

files = glob.glob (r"C:\Users\Downloads\All_Codes\image\1\*.png")
for myFile in files:
    image = cv2.imread (myFile,cv2.IMREAD_GRAYSCALE)
    print(image)
    #input_img_resize=cv2.resize(image,(64,64))
    train.append (image)
    train_labels.append([1])


print(len(train_labels))
print(train_labels)

train = np.array(train,dtype=object) #as mnist
train_labels = np.array(train_labels,dtype=object) #as mnist
# convert (number of images x height x width x number of channels) to (number of images x (height * width *3)) 
# for example (120 * 40 * 40 * 3)-> (120 * 4800)
train = np.reshape(train,(train.shape[0],64,64))


# save numpy array as .npy formats
np.save('train',train)
np.save('train_labels',train_labels)

但是我有一些错误。问题是,每次尝试读取图像并使用np.reshape重塑图像时,都会出现相同的错误。我搜索了很多,并使用了很多代码。他们都是一样的。我无法将(数据集中的图片数量)整形为(32,32),这是我要插入CNN模型的形状。我唯一确定的是我的数据集中的图像具有不同的形状。这就是为什么我在重塑它们时有些困难吗?那么使用“调整大小”和“调整形状”有什么意义呢?

第一个错误是:

ValueError: cannot reshape array of size 315 into shape (315,32,32)

此行:

train = np.reshape(train,[train.shape[0],32,32])

1 个答案:

答案 0 :(得分:0)

所以,我解决了这个问题。

import cv2
import glob
import numpy as np
import PIL.Image

#Train data
train = []
train_labels = []
files = glob.glob (r"\train\0\*.png") # your image path
for myFile in files:
    image = cv2.imread (myFile ,cv2.IMREAD_GRAYSCALE)
    input_img_resize=cv2.resize(image,(64,64))
    train.append (input_img_resize)
    train_labels.append([0])

#print(train) 
#print(len(train))

files = glob.glob (r"\train\1\*.png")
for myFile in files:
    image = cv2.imread (myFile,cv2.IMREAD_GRAYSCALE)
    input_img_resize=cv2.resize(image,(64,64))
    #print(input_img_resize)
    train.append (input_img_resize)
    train_labels.append([1])


print(len(train))
print(len(train_labels))

train = np.array(train,dtype="float32") #as mnist
train_labels = np.array(train_labels,dtype="float32") #as mnist
train = np.reshape(train,(-1,64,64,1))

我使用cv2.resize调整了图像的大小(在循环内) 然后使用np.reshape进行了重塑。

如果我依赖其中之一,则无法正常工作。我必须将它们都添加。 输出为:

315 #len表示x和y

315

(315,64,64)#cv2.resize之后

(315,1)

(315,64,64,1)#在np.reshape之后

(315,1)