使用Image.fromarray()时元组索引超出范围PIL

2021-12-08 05:49:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一些CIFAR10图像数据处理为图像块,以便在黑色画布上使用PIL进行打印。在从一个经过训练的模型中提取特征时,我成功地做到了这一点,但在使用Image.fromarray时,我一直得到IndexError: Tuple Index out of range

我的特征被塑造成形状(10000372)的测试数据。数据为32x32x3图像。 我加载cifar10数据,然后将数据展平,但仍会出现此错误

这是我的密码。其中一些是从https://medium.com/@pslinge144/representation-learning-cifar-10-23b0d9833c40借来的

import numpy as np 
from sklearn.manifold import TSNE
from time import time
from pathlib import Path
from PIL import Image
from time import time
from keras.datasets import cifar10

# Load the raw CIFAR-10 data
_, (X_test, y_test) = cifar10.load_data()

# normalize the xtest data
X_test = X_test.astype('float32')
X_test /= 255.0

features = X_test # this is (10000, 32, 32, 3) numpy array
features = np.reshape(features, (10000, 3072)) # flatten to 2d array
print(features.shape)

perplexities = [5, 30, 50, 100]
for perplexity in perplexities:
    print("Starting t-SNE on images now!")
    tsne = TSNE(n_components = 2, init = 'random', random_state = 0, perplexity = perplexity, learning_rate = 200).fit_transform(features)

    tx, ty = tsne[:,0], tsne[:,1] # grab tsne first and 2nd dimensions
    # min max normalize for plotting
    tx = (tx-np.min(tx)) / (np.max(tx) - np.min(tx))
    ty = (ty-np.min(ty)) / (np.max(ty) - np.min(ty))
    width = 4000
    height = 3000
    max_dim = 100
    full_image = Image.new('RGB', (width, height))
    for idx, x in enumerate(features):
        tile = Image.fromarray(np.uint8(x * 255), 'RGB') # rescale pixel values to [0,255] scale
        rs = max(1, tile.width / max_dim, tile.height / max_dim)
        tile = tile.resize((int(tile.width / rs),int(tile.height / rs)),Image.ANTIALIAS)
        full_image.paste(tile, (int((width-max_dim) * tx[idx]),int((height-max_dim) * ty[idx])))

        plots_output_path = Path('../data/processed/tSNE_plots').resolve()
        filename = "tsne_perplex%d_plot.png" % (perplexity)
        fullpath = plots_output_path.joinpath(filename).resolve()
        full_image.save(str(fullpath))

以下是错误:

Traceback (most recent call last):
  File "tSNE_image_thumbnail.py", line 80, in <module>
    tSNE_image(x_test, 1000, 200, plots_output_path, 2)
  File "tSNE_image_thumbnail.py", line 56, in tSNE_image
    tile = Image.fromarray(np.uint8(x * 255), 'RGB')
  File "/home/zw/src/image_classification_ML/venv/lib/python3.8/site-packages/PIL/Image.py", line 2728, in fromarray
    size = shape[1], shape[0]
IndexError: tuple index out of range

同样,当从CNN模型中提取特征并将其用于形状(10000512)密集层时,此代码工作正常。不知道为什么这会给我带来麻烦。有什么想法吗?提前谢谢