【发布时间】:2019-03-04 19:07:30
【问题描述】:
我正在尝试使用此页面中的代码: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 模型中的形状。我唯一确定的是我的数据集中的图像具有不同的形状。这就是我很难重塑它们的原因吗?那么使用“resize”和“reshape”有什么意义呢?
第一个错误是:
ValueError: cannot reshape array of size 315 into shape (315,32,32)
对于这一行:
train = np.reshape(train,[train.shape[0],32,32])
【问题讨论】:
-
如果
train具有形状 (315,) 和对象 dtype,则表示它是一维图像数组。reshape无法更改数组中的元素数量。它也不能将这 315 个图像合并到一个 3d 数组中。np.stack(train)可以做到这一点 - 只要所有图像具有相同的形状(和相同数量的颜色通道)。 -
在原始代码中,dtype='float32'。但是这条线会导致另一个错误。 [ValueError: setting an array element with a sequence.]这就是我将其更改为对象的原因。这与我的数组为什么是 1d 有什么关系吗?
-
[array([[ 78, 36, 75, ..., 0, 11, 0], [165, 86, 195, ..., 108, 53, 186], [ 93 , 103, 97, ..., 45, 69, 126], ..., [115, 106, 86, ..., 175, 167, 146], [143, 192, 155, ..., 117 , 124, 87], [170, 106, 141, ..., 103, 152, 201]], dtype=uint8) 这是我的图像在 np.reshape 之前的形状
-
这是在 cv2.resize 之后: [[ 77 90 144 ... 0 0 0] [ 0 240 2 ... 240 2 0] [164 14 0 ... 0 0 0] ... [ 0 0 0 ... 0 0 0] [144 144 144 ... 0 0 0] [ 0 0 0 ... 0 0 0]]
-
你显示了值的摘要,你没有显示
shape(像(32,32,3)或(64,64)这样的元组,