user824624
user824624

Reputation: 8080

store image into hdf5 store?

I need to store the RGB image data (96*96*3) into the HDF5 datastore, similar to the example shownhere where train_data size: (42000, 1, 28, 28). My image data dimension is like (image_num, 3, 96, 96).

Here is my code to store one image into the store.

test_data = np.zeros(( 1 ,3,96,96))

try:
    im = Image.open("/road8.jpg")
except:
    print "failed to load image: %s" %("/road8.jpg")

img = im.resize((96, 96), Image.BILINEAR)

test_data[0,:,:,:] = np.array(img).astype(np.float32) / 255 

with h5py.File(script_dir+"/test.h5", 'w') as f:
    f['data'] = test_data
    f.close()

However it gives me a error saying "could not broadcast input array from shape (96,96,3) into shape (3,96,96)", I know it means if I initialize the data like np.zeros(( 1 ,96,96, 3)), it will be ok. However I need to the order of the datastore has to be like np.zeros(( 1 ,3,96,96)). so the only way is to transform it after resize the image.

How would I do it?


I tried this solution

img = im.resize((96, 96))
img = np.transpose(img, (2,0,1))

but got a error saying

Traceback (most recent call last):
  File "vehicle_hdf5.py", line 51, in <module>
    img = np.transpose(img, (2,0,1))
  File "/Users/abc/anaconda/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 537, in transpose
    return transpose(axes)
  File "/Users/abc/anaconda/lib/python2.7/site-packages/PIL/Image.py", line 1936, in transpose
    return self._new(self.im.transpose(method))
TypeError: an integer is required

What does it mean ?

Upvotes: 0

Views: 1160

Answers (1)

P. Camilleri
P. Camilleri

Reputation: 13218

You could swap axes using np.swapaxes(im, 0, 2), but if you want to preserve the order "height before width", I suggest you use np.transpose as follows:

img = np.transpose(img, (2, 0, 1))
# first axis becomes third, second becomes first, third becomes second

Upvotes: 1

Related Questions