3
classify.py is an out-of-the-box image classifer callable from the command line.
5
By default it configures and runs the Caffe reference ImageNet model.
18
pycaffe_dir = os.path.dirname(__file__)
20
parser = argparse.ArgumentParser()
24
help="Input image, directory, or npy."
28
help="Output npy filename."
33
default=os.path.join(pycaffe_dir,
34
"../models/bvlc_reference_caffenet/deploy.prototxt"),
35
help="Model definition file."
39
default=os.path.join(pycaffe_dir,
40
"../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"),
41
help="Trained model weights file."
46
help="Switch for gpu computation."
51
help="Switch for prediction from center crop alone instead of " +
52
"averaging predictions across crops (default)."
57
help="Canonical 'height,width' dimensions of input images."
61
default=os.path.join(pycaffe_dir,
62
'caffe/imagenet/ilsvrc_2012_mean.npy'),
63
help="Data set image mean of [Channels x Height x Width] dimensions " +
64
"(numpy array). Set to '' for no mean subtraction."
69
help="Multiply input features by this scale to finish preprocessing."
75
help="Multiply raw input by this scale before preprocessing."
80
help="Order to permute input channels. The default converts " +
81
"RGB -> BGR since BGR is the Caffe default by way of OpenCV."
86
help="Image file extension to take as input when a directory " +
87
"is given as the input file."
89
args = parser.parse_args()
91
image_dims = [int(s) for s in args.images_dim.split(',')]
93
mean, channel_swap = None, None
95
mean = np.load(args.mean_file)
97
channel_swap = [int(s) for s in args.channel_swap.split(',')]
107
classifier = caffe.Classifier(args.model_def, args.pretrained_model,
108
image_dims=image_dims, mean=mean,
109
input_scale=args.input_scale, raw_scale=args.raw_scale,
110
channel_swap=channel_swap)
113
args.input_file = os.path.expanduser(args.input_file)
114
if args.input_file.endswith('npy'):
115
print("Loading file: %s" % args.input_file)
116
inputs = np.load(args.input_file)
117
elif os.path.isdir(args.input_file):
118
print("Loading folder: %s" % args.input_file)
119
inputs =[caffe.io.load_image(im_f)
120
for im_f in glob.glob(args.input_file + '/*.' + args.ext)]
122
print("Loading file: %s" % args.input_file)
123
inputs = [caffe.io.load_image(args.input_file)]
125
print("Classifying %d inputs." % len(inputs))
129
predictions = classifier.predict(inputs, not args.center_only)
130
print("Done in %.2f s." % (time.time() - start))
133
print("Saving results into %s" % args.output_file)
134
np.save(args.output_file, predictions)
137
if __name__ == '__main__':