Advertisement
Guest User

Untitled

a guest
Oct 3rd, 2016
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.58 KB | None | 0 0
  1. # imports and basic notebook setup
  2. from cStringIO import StringIO
  3. import numpy as np
  4. import scipy.ndimage as nd
  5. import PIL.Image
  6. import sys
  7. from IPython.display import clear_output, Image, display
  8. from google.protobuf import text_format
  9.  
  10. import caffe
  11.  
  12. # If your GPU supports CUDA and Caffe was built with CUDA support,
  13. # uncomment the following to run Caffe operations on the GPU.
  14. # caffe.set_mode_gpu()
  15. # caffe.set_device(0) # select GPU device if multiple devices exist
  16.  
  17. def saveimg(a, fname, fmt='jpeg'):
  18.     a = np.uint8(np.clip(a, 0, 255))
  19.     f = StringIO()
  20.     PIL.Image.fromarray(a).save(fname, fmt)
  21.     #display(Image(data=f.getvalue()))
  22.  
  23.  
  24. # a couple of utility functions for converting to and from Caffe's input image layout
  25. def preprocess(net, img):
  26.     return np.float32(np.rollaxis(img, 2)[::-1]) - net.transformer.mean['data']
  27. def deprocess(net, img):
  28.     return np.dstack((img + net.transformer.mean['data'])[::-1])
  29.  
  30. def objective_L2(dst):
  31.     dst.diff[:] = dst.data
  32.  
  33. def make_step(net, step_size=1.5, end='inception_4c/output',
  34.               jitter=32, clip=True, objective=objective_L2):
  35.     '''Basic gradient ascent step.'''
  36.  
  37.     src = net.blobs['data'] # input image is stored in Net's 'data' blob
  38.     dst = net.blobs[end]
  39.  
  40.     ox, oy = np.random.randint(-jitter, jitter+1, 2)
  41.     src.data[0] = np.roll(np.roll(src.data[0], ox, -1), oy, -2) # apply jitter shift
  42.  
  43.     net.forward(end=end)
  44.     objective(dst)  # specify the optimization objective
  45.     net.backward(start=end)
  46.     g = src.diff[0]
  47.     # apply normalized ascent step to the input image
  48.     src.data[:] += step_size/np.abs(g).mean() * g
  49.  
  50.     src.data[0] = np.roll(np.roll(src.data[0], -ox, -1), -oy, -2) # unshift image
  51.  
  52.     if clip:
  53.         bias = net.transformer.mean['data']
  54.         src.data[:] = np.clip(src.data, -bias, 255-bias)
  55.  
  56. def deepdream(net, base_img, iter_n=10, octave_n=4, octave_scale=1.4,
  57.               end='inception_4c/output', clip=True, **step_params):
  58.     # prepare base images for all octaves
  59.     octaves = [preprocess(net, base_img)]
  60.     for i in xrange(octave_n-1):
  61.         octaves.append(nd.zoom(octaves[-1], (1, 1.0/octave_scale,1.0/octave_scale), order=1))
  62.  
  63.     src = net.blobs['data']
  64.     detail = np.zeros_like(octaves[-1]) # allocate image for network-produced details
  65.     for octave, octave_base in enumerate(octaves[::-1]):
  66.         h, w = octave_base.shape[-2:]
  67.         if octave > 0:
  68.             # upscale details from the previous octave
  69.             h1, w1 = detail.shape[-2:]
  70.             detail = nd.zoom(detail, (1, 1.0*h/h1,1.0*w/w1), order=1)
  71.  
  72.         src.reshape(1,3,h,w) # resize the network's input image size
  73.         src.data[0] = octave_base+detail
  74.  
  75.         for i in xrange(iter_n):
  76.             make_step(net, end=end, clip=clip, **step_params)
  77.  
  78.             # visualization
  79.             vis = deprocess(net, src.data[0])
  80.             if not clip: # adjust image contrast if clipping is disabled
  81.                 vis = vis*(255.0/np.percentile(vis, 99.98))
  82.             #showarray(vis)
  83.             print octave, i, end, vis.shape
  84.             clear_output(wait=True)
  85.  
  86.         # extract details produced on the current octave
  87.         detail = src.data[0]-octave_base
  88.     # returning the resulting image
  89.     return deprocess(net, src.data[0])
  90.  
  91. def resize_image(data, sz=(256, 256)):
  92.     """
  93.    Resize image. Please use this resize logic for best results instead of the
  94.    caffe, since it was used to generate training dataset
  95.    :param str data:
  96.        The image data
  97.    :param sz tuple:
  98.        The resized image dimensions
  99.    :returns bytearray:
  100.        A byte array with the resized image
  101.    """
  102.     img_data = str(data)
  103.     im = PIL.Image.open(StringIO(img_data))
  104.     if im.mode != "RGB":
  105.         im = im.convert('RGB')
  106.     imr = im.resize(sz, resample=PIL.Image.BILINEAR)
  107.     fh_im = StringIO()
  108.     imr.save(fh_im, format='JPEG')
  109.     fh_im.seek(0)
  110.     return bytearray(fh_im.read())
  111.  
  112.  
  113. def make_nsfw_input(filename, net):
  114.     image_data = open(filename).read()
  115.     img_data_rs = resize_image(image_data, sz=(256, 256))
  116.     caffe_image = caffe.io.load_image(StringIO(img_data_rs))
  117.     H, W, _ = caffe_image.shape
  118.     _, _, h, w = net.blobs['data'].data.shape
  119.     h_off = max((H - h) / 2, 0)
  120.     w_off = max((W - w) / 2, 0)
  121.     input_cropped = caffe_image[h_off:h_off + h, w_off:w_off + w, :]
  122.     caffe_transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
  123.     caffe_transformer.set_transpose('data', (2, 0, 1))  # move image channels to outermost
  124.     caffe_transformer.set_mean('data', np.array([104, 117, 123]))  # subtract the dataset-mean value in each channel
  125.     caffe_transformer.set_raw_scale('data', 255)  # rescale from [0, 1] to [0, 255]
  126.     caffe_transformer.set_channel_swap('data', (2, 1, 0))  # swap channels from RGB to BGR
  127.     transformed_image = caffe_transformer.preprocess('data', input_cropped)
  128.     transformed_image.shape = (1,) + transformed_image.shape
  129.     return transformed_image
  130.  
  131. def main(argv):
  132.     input_name = argv[1]
  133.     input_img = np.float32(PIL.Image.open(input_name))
  134.  
  135.     model_path = '../nsfw_model/' # substitute your path here
  136.     net_fn   = model_path + 'deploy.prototxt'
  137.     param_fn = model_path + 'resnet_50_1by2_nsfw.caffemodel'
  138.  
  139.     # Patching model to be able to compute gradients.
  140.     # Note that you can also manually add "force_backward: true" line to "deploy.prototxt".
  141.     model = caffe.io.caffe_pb2.NetParameter()
  142.     text_format.Merge(open(net_fn).read(), model)
  143.     model.force_backward = True
  144.     open('tmp.prototxt', 'w').write(str(model))
  145.  
  146.     net = caffe.Classifier('tmp.prototxt', param_fn,
  147.                            mean = np.float32([104.0, 117.0, 123.0]), # ImageNet mean, training set dependent
  148.                            channel_swap = (2,1,0)) # the reference model has channels in BGR order instead of RGB
  149.  
  150.  
  151.     #layer_name = 'conv_stage2_block3_branch2a'
  152.     layer_name = 'conv_stage3_block0_proj_shortcut' #conv_stage1_block3_branch2a'
  153.  
  154.     # compute input according to classify_nsfw.py
  155.     transformed_image = make_nsfw_input(input_name, net)
  156.  
  157.     if (len(argv) == 2):
  158.         print "Computing NSFW score"
  159.         input_name = net.inputs[0]
  160.         all_outputs = net.forward_all(blobs=['prob'], **{input_name: transformed_image})
  161.  
  162.         outputs = all_outputs['prob'][0].astype(float)
  163.  
  164.         print "score: ", outputs[1]
  165.  
  166.         return
  167.  
  168.     output_name = argv[2]
  169.  
  170.     if len(argv) > 3:
  171.         guide_name = argv[3]
  172.         transformed_guide = make_nsfw_input(guide_name, net)
  173.         input_name = net.inputs[0]
  174.         all_outputs = net.forward_all(blobs=['prob', layer_name], **{input_name: transformed_guide})
  175.         guide_features = all_outputs[layer_name].copy();
  176.         print "guide score: ", all_outputs['prob'][0].astype(float)[1]
  177.  
  178.         def objective_guide(dst):
  179.             x = dst.data[0].copy()
  180.             y = guide_features
  181.             ch = x.shape[0]
  182.             x = x.reshape(ch,-1)
  183.             y = y.reshape(ch,-1)
  184.             A = x.T.dot(y) # compute the matrix of dot-products with guide features
  185.             dst.diff[0].reshape(ch,-1)[:] = y[:,A.argmax(1)] # select ones that match best
  186.  
  187.         output_img=deepdream(net, input_img, 10, octave_n=6, end=layer_name, objective=objective_guide)
  188.         print "FIN DU REVE"
  189.     else:
  190.         #img2=deepdream(net, img, 10, 6, end='conv_stage3_block0_proj_shortcut') #conv_stage3_block1_branch2b') #eltwise_stage3_block1')
  191.         output_img=deepdream(net, input_img, 10, 8, end=layer_name)
  192.  
  193.     saveimg(output_img, output_name)
  194.  
  195.  
  196. if __name__ == '__main__':
  197.     main(sys.argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement