我正在尝试运行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
中答案 0 :(得分:2)
您已在img=[]
块(本地)内定义except
。这就是为什么它没有访问块外的原因。在块外定义它。
def get_class(img_path):
return int(img_path.split('/')[-2])
imgs=[]
labels=[]
#Your code