ValueError: cannot reshape array of size 230 into shape (3,600,800)

ValueError: cannot reshape array of size 230 into shape (3,600,800)

我正在从 2 个不同的文件夹中读取 230 张图像作为数组并调整它的大小,以保持每张图像的纵横比不变(调整后的图像大小宽度 = 600 * 高度 = 800)。之后我试图将标签和图像数组分成两个不同的列表。现在,在将图像数组列表提供给 CNN 模型之前,我将其重塑为 reshape([-1, 3, 600, 800]) 格式,但出现错误:

ValueError:无法将大小为 230 的数组重塑为形状 (3,600,800)

如何将其重塑为上述格式?

编写的代码是:

def create_data():
    for category in LABELS:  
        path = os.path.join(DATADIR,category)  
        class_num = LABELS.index(category)  # get the classification  (0 or a 1).
        for img in tqdm(os.listdir(path)):
            img_array = cv2.imread(os.path.join(path,img))  # convert to array
            fac = np.array(img_array).shape[0]/np.array(img_array).shape[1]
            new_array = cv2.resize(img_array, (600, int(np.ceil((fac*600)))))# resize to normalize data size
            data.append([new_array, class_num])  # add to data


create_data()


Xtest = []
ytest = []


for features,label in data:
    Xtest.append(features)
    ytest.append(label)

X = np.array(Xtest).reshape([-1, 3, 600, 800]) 

不要调整整个数组的大小,单独调整数组中每个图像的大小。

X = np.array(Xtest).reshape([-1, 3, 600, 800]) 

这将创建一个包含 230 个项目的一维数组。如果您对其调用 reshape,numpy 将尝试将此数组作为一个整体进行整形,而不是其中的单个图像!

cv2.resize之后,你的图片高度都是600,但是宽度不同。这意味着它们都有不同数量的像素,可能太多或太少而无法形成您期望的输出形状。您也无法将这些图像连接成一个大数组。

您需要 crop/pad 所有图片都具有相同的尺寸。