python - key 错误 : "Unable to open object (object ' imgs' doesn't exist)"

标签 python python-3.x machine-learning deep-learning keras

我正在尝试运行 Keras 教程中的源代码进行图像识别。我收到此错误,

Traceback (most recent call last):
File "ty.py", line 52, in <module>
X, Y = hf['imgs'][:], hf['labels'][:]
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "C:\Users\alams\Anaconda3\envs\tensorflow\lib\site-
packages\h5py\_hl\group.py", line 167, in __getitem__
oid = h5o.open(self.id, self._e(name), lapl=self._lapl)
File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py\h5o.pyx", line 190, in h5py.h5o.open
KeyError: "Unable to open object (object 'imgs' doesn't exist)"
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "ty.py", line 66, in <module>
label = get_class(img_path)
File "ty.py", line 48, in get_class
return int(img_path.split('/')[-2])
ValueError: invalid literal for int() with base 10: 'Final_Training'

这是我的源代码:

def get_class(img_path):
   return int(img_path.split('/')[-2])
try:
    with  h5py.File('X.h5') as hf: 
      X, Y = hf['imgs'][:], hf['labels'][:]

except (IOError,OSError, KeyError):  
    root_dir = 'Data/Final_Training/Images/'
    imgs = []
    labels = []

    all_img_paths = glob.glob(os.path.join(root_dir, '*/*.ppm'))
    np.random.shuffle(all_img_paths)
    for img_path in all_img_paths:
        try:
            img = preprocess_img(io.imread(img_path))
            label = get_class(img_path)
            imgs.append(img)
            labels.append(label)
        except (IOError, OSError):
            print('missed', img_path)
            pass

X = np.array(imgs, dtype='float32')
Y = np.eye(NUM_CLASSES, dtype='uint8')[labels]

with h5py.File('X.h5','w') as hf:
    hf.create_dataset('imgs', data=X)
    hf.create_dataset('labels', data=Y)

我尝试通过从第一个函数的返回中删除 int Conversion 来运行此代码。但似乎所有的值都没有写在 X.h5

最佳答案

您已在 except block (本地)内定义了 img=[]。这就是为什么它无法访问 block 外的原因。在 block 之外定义它。

 def get_class(img_path):
    return int(img_path.split('/')[-2])

 imgs=[]
 labels=[]

 #Your code

关于python - key 错误 : "Unable to open object (object ' imgs' doesn't exist)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48074705/

相关文章:

Python:time.clock()与实际执行时间不匹配

python - 使用来自三列的分组问题制作数据框

django - 无法让 sql server 与 django azure web 应用程序一起使用

python - 在矩阵中重复每一行 n 次,并在每个部分旁边添加一列 1*n

machine-learning - 为什么要使用 CH 和 SIL 来查找 Elbow(或使用 L 方法)来选择簇数量?

python - 如何在Python中模拟补丁ctypes.WinDLL?

python - isinstance() 方法在 Python 3 中返回错误答案

python - ValueError : X. shape[1] = 2 should be equal to 13, 训练时的特征数

python - 使用 sklearn 聚类单变量时间序列

python - 如何返回与 pandas 中包含括号的字符串的匹配项?