numpy - 尝试可视化图像时出现值错误
问题描述
我正在尝试可视化属于不同类别的一些图像。类别是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)
解决方案
推荐阅读
- rest - 使用 Perl 使用 Basic auth 对 REST API 执行 POST 请求
- c# - 使用多级层次关系(SQL 或 LINQ)对多表连接进行搜索查询
- windows - 无法使批处理宏工作(cmd.exe)?
- postgresql - Prisma - Postgres 事务 - 并发事务中读取增量数的问题
- c++ - 实例化变量模板时 gcc 和 -Wfloat-conversion 不一致
- python - python元素树插入在所需位置和最后添加两次子项
- java - 在 Vaadin Grid 中使用多个模板
- blockchain - Solidity - 建立一个智能合约,将以太币返还给发送者
- python - 如何使用从python中的文本文件形成的嵌套字典中的用户名调用特定字典
- istio - Istio (envoy) 匹配没有标头的速率限制