Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. def tffunc(*argtypes):
  2. '''Helper that transforms TF-graph generating function into a regular one.
  3. See "resize" function below.
  4. '''
  5. placeholders = list(map(tf.placeholder, argtypes))
  6. def wrap(f):
  7. out = f(*placeholders)
  8. def wrapper(*args, **kw):
  9. return out.eval(dict(zip(placeholders, args)), session=kw.get('session'))
  10. return wrapper
  11. return wrap
  12.  
  13. # Helper function that uses TF to resize an image
  14. def resize(img, size):
  15. img = tf.expand_dims(img, 0)
  16. return tf.image.resize_bilinear(img, size)[0,:,:,:]
  17. resize = tffunc(np.float32, np.int32)(resize)
  18.  
  19.  
  20. def calc_grad_tiled(img, t_grad, tile_size=512):
  21. '''Compute the value of tensor t_grad over the image in a tiled way.
  22. Random shifts are applied to the image to blur tile boundaries over
  23. multiple iterations.'''
  24. sz = tile_size
  25. h, w = img.shape[:2]
  26. sx, sy = np.random.randint(sz, size=2)
  27. img_shift = np.roll(np.roll(img, sx, 1), sy, 0)
  28. grad = np.zeros_like(img)
  29. for y in range(0, max(h-sz//2, sz),sz):
  30. for x in range(0, max(w-sz//2, sz),sz):
  31. sub = img_shift[y:y+sz,x:x+sz]
  32. g = sess.run(t_grad, {t_input:sub})
  33. grad[y:y+sz,x:x+sz] = g
  34. return np.roll(np.roll(grad, -sx, 1), -sy, 0)
  35.  
  36.  
  37. def render_multiscale(t_obj, img0=img_noise, iter_n=10, step=1.0, octave_n=3, octave_scale=1.4):
  38. t_score = tf.reduce_mean(t_obj) # defining the optimization objective
  39. t_grad = tf.gradients(t_score, t_input)[0] # behold the power of automatic differentiation!
  40.  
  41. img = img0.copy()
  42. for octave in range(octave_n):
  43. if octave>0:
  44. hw = np.float32(img.shape[:2])*octave_scale
  45. img = resize(img, np.int32(hw))
  46. for i in range(iter_n):
  47. g = calc_grad_tiled(img, t_grad)
  48. # normalizing the gradient, so the same step size should work
  49. g /= g.std()+1e-8 # for different layers and networks
  50. img += g*step
  51. print('.', end = ' ')
  52. clear_output()
  53. showarray(visstd(img))
  54.  
  55. render_multiscale(T(layer)[:,:,:,channel])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement