Classifying Grayscale Images using Pycaffe

If you have trained a model with 1-dimensional gray image, and want to classify another gray image, the following is the hack worked for me:

  1. copy the offical classify.py in $CAFFE_ROOT/python/classify.py
  2. specify input_dim as 1, 1, x, x in deploy.prototxt
  3. change all call to caffe.io.load_image(fname) in classify.py to caffe.io.load_image(fname, False) because if you do not specify the second parameter as False, True will be used by default, the meaning of the second parameter is to tell load_image whether the image is color or gray, if it’s in color, then the returned image will have shape (width, height, 3) or (width, height, 4) depending on whether the alpha channel exists. If you specify False, the shape will be (width, height, 1) as you want.
  4. specify –channel_swap ‘0’ in python classify.py because this value is to reorder RGB to BGR, let’s say we have an image im, im is in numpy array format, and im.shape = (10, 10, 3), then caffe will do im = im[:, :, channel_wap] to swap channels, if you do not specify --channel_swap, it will be "2,1,0" by default, then in caffe, im = im[:, :, [2, 1, 0]], but the gray image’s shape is really (10, 10, 1) (if you follow the 2 step), so an index out of bounds exception will be raised. So just specify ‘0’ to --channel_swap, then caffe will run im = im[:, :, [0]], that’s fine.

then just use the official classify.py.

Here is the gist of classify.py and test.sh worked for me.
classify.py: https://gist.github.com/uronce-cc/869afe1bd85e79dda111
test.sh: https://gist.github.com/uronce-cc/e834e9cd2a0a62ceb5d5

Hope it will work for you too.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s