Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.41 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Copyright 2016 Yahoo Inc.
  4. Licensed under the terms of the 2 clause BSD license.
  5. Please see LICENSE file in the project root for terms.
  6. """
  7.  
  8. import numpy as np
  9. import os
  10. import sys
  11. import argparse
  12. import glob
  13. import time
  14. from StringIO import StringIO
  15. from PIL import Image
  16. import cv2
  17. import caffe
  18.  
  19.  
  20. def resize_image(data, sz=(256, 256)):
  21. """
  22. Resize image. Please use this resize logic for best results instead of the
  23. caffe, since it was used to generate training dataset
  24. :param str data:
  25. The image data
  26. :param sz tuple:
  27. The resized image dimensions
  28. :returns bytearray:
  29. A byte array with the resized image
  30. """
  31. img_data = str(data)
  32. im = Image.open(StringIO(img_data))
  33. if im.mode != "RGB":
  34. im = im.convert('RGB')
  35. imr = im.resize(sz, resample=Image.BILINEAR)
  36. fh_im = StringIO()
  37. imr.save(fh_im, format='JPEG')
  38. fh_im.seek(0)
  39. return bytearray(fh_im.read())
  40.  
  41. def caffe_preprocess_and_compute(mode, pimg, caffe_transformer=None, caffe_net=None,
  42. output_layers=None):
  43. """
  44. Run a Caffe network on an input image after preprocessing it to prepare
  45. it for Caffe.
  46. :param PIL.Image pimg:
  47. PIL image to be input into Caffe.
  48. :param caffe.Net caffe_net:
  49. A Caffe network with which to process pimg afrer preprocessing.
  50. :param list output_layers:
  51. A list of the names of the layers from caffe_net whose outputs are to
  52. to be returned. If this is None, the default outputs for the network
  53. are returned.
  54. :return:
  55. Returns the requested outputs from the Caffe net.
  56. """
  57. if caffe_net is not None:
  58.  
  59. # Grab the default output names if none were requested specifically.
  60. if output_layers is None:
  61. output_layers = caffe_net.outputs
  62.  
  63. if mode == "opencv":
  64. image = cv2.imread(pimg)
  65. print(image[0][0][0])
  66. image = cv2.resize(image, (224, 224), 0, 0, cv2.INTER_CUBIC)
  67. # image = image / 255.0
  68. print(image.shape)
  69. print(image[0][0][0])
  70. transformed_image = caffe_transformer.preprocess('data', image)
  71. print(transformed_image[0][0][0])
  72. elif mode == "orig":
  73. img_data_rs = resize_image(pimg, sz=(256, 256))
  74. image = caffe.io.load_image(StringIO(img_data_rs))
  75. H, W, _ = image.shape
  76. _, _, h, w = caffe_net.blobs['data'].data.shape
  77. h_off = max((H - h) / 2, 0)
  78. w_off = max((W - w) / 2, 0)
  79. crop = image[h_off:h_off + h, w_off:w_off + w, :]
  80. transformed_image = caffe_transformer.preprocess('data', crop)
  81. elif mode == "nocrop":
  82. img_data_rs = resize_image(pimg, sz=(224, 224))
  83. image = caffe.io.load_image(StringIO(img_data_rs))
  84. transformed_image = caffe_transformer.preprocess('data', image)
  85. elif mode == "caffe":
  86. image = caffe.io.load_image(pimg)
  87. image = caffe.io.resize_image(image, (224, 224), interp_order=1)
  88. transformed_image = caffe_transformer.preprocess('data', image)
  89.  
  90.  
  91. # np.savetxt("nopil-data.txt", transformed_image.flatten(), '%.16f')
  92.  
  93. transformed_image.shape = (1,) + transformed_image.shape
  94.  
  95. input_name = caffe_net.inputs[0]
  96. all_outputs = caffe_net.forward_all(blobs=output_layers,
  97. **{input_name: transformed_image})
  98.  
  99. outputs = all_outputs[output_layers[0]][0].astype(float)
  100. return outputs
  101. else:
  102. return []
  103.  
  104.  
  105. def main(argv):
  106. pycaffe_dir = os.path.dirname(__file__)
  107.  
  108. parser = argparse.ArgumentParser()
  109. # Required arguments: input file.
  110. parser.add_argument(
  111. "input_file",
  112. help="Path to the input image file"
  113. )
  114.  
  115. # Optional arguments.
  116. parser.add_argument(
  117. "--model_def",
  118. help="Model definition file."
  119. )
  120. parser.add_argument(
  121. "--pretrained_model",
  122. help="Trained model weights file."
  123. )
  124.  
  125. parser.add_argument(
  126. "--mode",
  127. help="'orig': original script, 'nocrop': original without center crop, 'opencv': use opencv to load and resize image, 'caffe': use caffe to load and resize image'")
  128.  
  129. args = parser.parse_args()
  130. if args.mode == "orig" or args.mode == "nocrop":
  131. image_data = open(args.input_file).read()
  132. else:
  133. image_data = args.input_file
  134.  
  135. # Pre-load caffe model.
  136. nsfw_net = caffe.Net(args.model_def, # pylint: disable=invalid-name
  137. args.pretrained_model, caffe.TEST)
  138.  
  139. # Load transformer
  140. # Note that the parameters are hard-coded for best results
  141. caffe_transformer = caffe.io.Transformer({'data': nsfw_net.blobs['data'].data.shape})
  142. caffe_transformer.set_transpose('data', (2, 0, 1)) # move image channels to outermost
  143. caffe_transformer.set_mean('data', np.array([104, 117, 123])) # subtract the dataset-mean value in each channel
  144. if args.mode != "opencv":
  145. caffe_transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]
  146. caffe_transformer.set_channel_swap('data', (2, 1, 0)) # swap channels from RGB to BGR
  147.  
  148. # Classify.
  149. scores = caffe_preprocess_and_compute(args.mode, image_data, caffe_transformer=caffe_transformer, caffe_net=nsfw_net, output_layers=['prob'])
  150.  
  151. # Scores is the array containing SFW / NSFW image probabilities
  152. # scores[1] indicates the NSFW probability
  153. print "NSFW score: " , scores[1]
  154.  
  155.  
  156.  
  157. if __name__ == '__main__':
  158. main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement