Reputation: 61
I am trying to run a source code from a Keras tutorial for image recognition. I'm getting this error,
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'
This is my source code:
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)
I tried to run this code by removing the int Conversion from the return of the first function. But seems like all the values are not write in X.h5
Upvotes: 2
Views: 4295
Reputation: 13426
You have defined img=[]
inside except
block (locally). That's why it doesn't have access outside the block. Define it outside the block.
def get_class(img_path):
return int(img_path.split('/')[-2])
imgs=[]
labels=[]
#Your code
Upvotes: 2