首页 > 解决方案 > 尝试可视化图像时出现值错误

问题描述

我正在尝试可视化属于不同类别的一些图像。类别是class0,class1,class2,它们分别表示健康、covid 和肺炎肺的 X 射线照片。例如,请参见下面的 covid 肺图片:

在此处输入图像描述

我创建了三个包含训练、测试和验证数据的数据集。请看下面的代码:

import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
from matplotlib import pyplot as plt
import numpy as np

#Creating three dataframes reading .txt files
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
#Change 0,1,2 to categorical class class0,class1,class2
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#Final training, test and validation data
datagen=ImageDataGenerator(rescale=None)
train_generator=datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256), batch_size=32)
test_generator=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256), batch_size=15)
validation_generator=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256), batch_size=21)

现在,可视化一张图片的代码:

first_image = train_generator[0]
first_image = np.array(first_image, dtype='float')
pixels = first_image.reshape((28, 28))
plt.imshow(pixels, cmap='gray')
plt.show()

我收到以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-3-b237e88f96dd> in <module>
      1 first_image = train_generator[0]
----> 2 first_image = np.array(first_image, dtype='float')
      3 pixels = first_image.reshape((28, 28))
      4 plt.imshow(pixels, cmap='gray')
      5 plt.show()

ValueError: could not broadcast input array from shape (32,256,256,3) into shape (32)

此外,有没有办法可视化对应于特定类的图像?

如果不是first_image= first_image[0], I do first_image= first_image[0][0]. 然后弹出的错误是:

 ValueError                                Traceback (most recent call last)
<ipython-input-4-0664c7dc8c6b> in <module>
      1 first_image = train_generator[0][0]
      2 first_image = np.array(first_image, dtype='float')
----> 3 pixels = first_image.reshape((28, 28))
      4 plt.imshow(pixels, cmap='gray')
      5 plt.show()

ValueError: cannot reshape array of size 6291456 into shape (28,28)

标签: numpymatplotlibmachine-learningkeras

解决方案


推荐阅读