无法在python中读取.npz文件

2024-06-11 12:41:41 发布

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

我使用以下代码创建了一个npz(压缩文件):

import pandas as pd
from tqdm import tqdm
from keras.preprocessing import image
import numpy as np    # for mathematical operations
from keras.preprocessing import image   # for preprocessing the images

anomoly_data = pd.read_csv('/code_data/anomoly_data.csv')
f = open('/code_data/anomoly_data.npz', 'wb')
for i in tqdm(range(anomoly_data.shape[0])):
    img = image.load_img(anomoly_data['image'][i], target_size=(224,224,3))
    # converting it to array
    img = image.img_to_array(img)
    # normalizing the pixel value
    img = img/255
    np.savez_compressed(f, img)
f.close()

压缩文件的大小为52GBs,这表示它包含所有图像的数据。 在anomoly_data.csv中,我有每个图像的路径,.csv中的条目是

188604

现在,我尝试使用以下代码读取所有压缩图像的数据:

f=open("/code_data/anomoly_data.npz","rb")
for i in tqdm(range(anomoly_data.shape[0])):
    img=np.load(f)
    print(img)

然后我得到一个错误,告诉我压缩文件中只有一个数据数组,错误:

<numpy.lib.npyio.NpzFile object at 0x7fdfd1d437c0>

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-29b2878e9fe9> in <module>
      1 f=open("/code_data/anomoly_data.npz","rb")
      2 for i in range(anomoly_data.shape[0]):
----> 3     img=np.load(f)
      4     print(img)
      5 

~/Programs/Anaconda/lib/python3.8/site-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
    442             # Try a pickle
    443             if not allow_pickle:
--> 444                 raise ValueError("Cannot load file containing pickled data "
    445                                  "when allow_pickle=False")
    446             try:

ValueError: Cannot load file containing pickled data when allow_pickle=False

但我只得到了一个数组的数据,这表明要么只有一个图像的数据,要么它是变形的。这意味着压缩文件未正确生成。 有没有更好的办法


Tags: csv数据inimageimportimgfordata