Advertisement
pongfactory

classify-py

Jun 15th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.36 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. classify.py is an out-of-the-box image classifer callable from the command line.
  4.  
  5. By default it configures and runs the Caffe reference ImageNet model.
  6. """
  7. import numpy as np
  8. import os
  9. import sys
  10. import argparse
  11. import glob
  12. import time
  13. import pandas as pd
  14. import caffe
  15.  
  16.  
  17. def main(argv):
  18.     pycaffe_dir = os.path.dirname(__file__)
  19.  
  20.     parser = argparse.ArgumentParser()
  21.     # Required arguments: input and output files.
  22.  
  23. ##
  24.     parser.add_argument(
  25.         "--print_results",
  26.         action='store_true',
  27.         help="Write output text to stdout rather than serializing to a file."
  28.     )
  29.     parser.add_argument(
  30.         "--labels_file",
  31.         default=os.path.join(pycaffe_dir,"../data/ilsvrc12/synset_words.txt"),
  32.         help="Readable label definition file."
  33.     )  
  34. ##
  35.     parser.add_argument(
  36.         "input_file",
  37.         help="Input image, directory, or npy."
  38.     )
  39.     parser.add_argument(
  40.         "output_file",
  41.         help="Output npy filename."
  42.     )
  43.     # Optional arguments.
  44.     parser.add_argument(
  45.         "--model_def",
  46.         default=os.path.join(pycaffe_dir,
  47.                 "../models/bvlc_reference_caffenet/deploy.prototxt"),
  48.         help="Model definition file."
  49.     )
  50.     parser.add_argument(
  51.         "--pretrained_model",
  52.         default=os.path.join(pycaffe_dir,
  53.                 "../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"),
  54.         help="Trained model weights file."
  55.     )
  56.     parser.add_argument(
  57.         "--gpu",
  58.         action='store_true',
  59.         help="Switch for gpu computation."
  60.     )
  61.     parser.add_argument(
  62.         "--center_only",
  63.         action='store_true',
  64.         help="Switch for prediction from center crop alone instead of " +
  65.              "averaging predictions across crops (default)."
  66.     )
  67.     parser.add_argument(
  68.         "--images_dim",
  69.         default='256,256',
  70.         help="Canonical 'height,width' dimensions of input images."
  71.     )
  72.     parser.add_argument(
  73.         "--mean_file",
  74.         default=os.path.join(pycaffe_dir,
  75.                              'caffe/imagenet/ilsvrc_2012_mean.npy'),
  76.         help="Data set image mean of [Channels x Height x Width] dimensions " +
  77.              "(numpy array). Set to '' for no mean subtraction."
  78.     )
  79.     parser.add_argument(
  80.         "--input_scale",
  81.         type=float,
  82.         help="Multiply input features by this scale to finish preprocessing."
  83.     )
  84.     parser.add_argument(
  85.         "--raw_scale",
  86.         type=float,
  87.         default=255.0,
  88.         help="Multiply raw input by this scale before preprocessing."
  89.     )
  90.     parser.add_argument(
  91.         "--channel_swap",
  92.         default='2,1,0',
  93.         help="Order to permute input channels. The default converts " +
  94.              "RGB -> BGR since BGR is the Caffe default by way of OpenCV."
  95.     )
  96.     parser.add_argument(
  97.         "--ext",
  98.         default='jpg',
  99.         help="Image file extension to take as input when a directory " +
  100.              "is given as the input file."
  101.     )
  102.  
  103. ###
  104.     args = parser.parse_args()
  105. ###
  106.     image_dims = [int(s) for s in args.images_dim.split(',')]
  107.  
  108.     mean, channel_swap = None, None
  109.     if args.mean_file:
  110.         mean = np.load(args.mean_file)
  111.     if args.channel_swap:
  112.         channel_swap = [int(s) for s in args.channel_swap.split(',')]
  113.  
  114.     if args.gpu:
  115.         caffe.set_mode_gpu()
  116.         print("GPU mode")
  117.     else:
  118.         caffe.set_mode_cpu()
  119.         print("CPU mode")
  120.  
  121.     # Make classifier.
  122.     classifier = caffe.Classifier(args.model_def, args.pretrained_model,
  123.             image_dims=image_dims, mean=mean,
  124.             input_scale=args.input_scale, raw_scale=args.raw_scale,
  125.             channel_swap=channel_swap)
  126.  
  127.     # Load numpy array (.npy), directory glob (*.jpg), or image file.
  128.     args.input_file = os.path.expanduser(args.input_file)
  129.     if args.input_file.endswith('npy'):
  130.         print("Loading file: %s" % args.input_file)
  131.         inputs = np.load(args.input_file)
  132.     elif os.path.isdir(args.input_file):
  133.         print("Loading folder: %s" % args.input_file)
  134.         inputs =[caffe.io.load_image(im_f)
  135.                  for im_f in glob.glob(args.input_file + '/*.' + args.ext)]
  136.     else:
  137.         print("Loading file: %s" % args.input_file)
  138.         inputs = [caffe.io.load_image(args.input_file)]
  139.  
  140.     print("Classifying %d inputs." % len(inputs))
  141.  
  142.     # Classify.
  143.   #  start = time.time()
  144.    # predictions = classifier.predict(inputs, not args.center_only)
  145.     #print("Done in %.2f s." % (time.time() - start))
  146.  
  147.     start = time.time()
  148.     scores = classifier.predict(inputs, not args.center_only).flatten()
  149.     print("Done in %.2f s." % (time.time() - start))
  150.  
  151.     if args.print_results:
  152.         with open(args.labels_file) as f:
  153.             labels_df = pd.DataFrame([{'synset_id':l.strip().split(' ')[0], 'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]} for l in f.readlines()])
  154.             labels = labels_df.sort('synset_id')['name'].values
  155.    
  156.             indices =(-scores).argsort()[:5]
  157.             predictions = labels[indices]
  158.    
  159.             meta = [(p, '%.5f' % scores[i]) for i,p in zip(indices, predictions)]
  160.             print meta
  161.  
  162.     # Save
  163.     print("Saving results into %s" % args.output_file)
  164.     np.save(args.output_file, predictions)
  165.  
  166.    # print(predictions)
  167.  
  168. if __name__ == '__main__':
  169.     main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement