Advertisement
Guest User

Untitled

a guest
Oct 11th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. # In[25]:
  5.  
  6.  
  7. import foolbox
  8. from foolbox.models import KerasModel
  9. from foolbox.attacks import LBFGSAttack
  10. from foolbox.criteria import TargetClassProbability, TargetClass
  11. import numpy as np
  12. import keras
  13. from keras.applications.mobilenet import preprocess_input
  14. from keras.models import load_model
  15. from keras.preprocessing.image import img_to_array, array_to_img
  16. from PIL import Image
  17. from imagehash import phash
  18. # import matplotlib.pyplot as plt
  19. # get_ipython().magic(u'matplotlib inline')
  20.  
  21.  
  22. IMAGE_DIMS = (224, 224)
  23. TREE_FROG_IDX = 31
  24. TREE_FROG_STR = "tree_frog"
  25.  
  26.  
  27. # I'm pretty sure I borrowed this function from somewhere, but cannot remember
  28. # the source to cite them properly.
  29. def hash_hamming_distance(h1, h2):
  30. s1 = str(h1)
  31. s2 = str(h2)
  32. return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(s1, s2)))
  33.  
  34.  
  35. def is_similar_img(path1, path2):
  36. image1 = Image.open(path1)
  37. image2 = Image.open(path2)
  38.  
  39. dist = hash_hamming_distance(phash(image1), phash(image2))
  40. return dist <= 2
  41.  
  42.  
  43. def prepare_image(image, target=IMAGE_DIMS):
  44. # if the image mode is not RGB, convert it
  45. if image.mode != "RGB":
  46. image = image.convert("RGB")
  47.  
  48. # resize the input image and preprocess it
  49. image = image.resize(target)
  50. image = img_to_array(image)
  51. image = preprocess_input(image)
  52. # return the processed image
  53. return image
  54.  
  55.  
  56. # In[26]:
  57.  
  58.  
  59. def create_img(img_path, img_res_path, model_path, target_str, target_idx, des_conf=0.95):
  60. test = Image.open(img_path).resize(IMAGE_DIMS)
  61. test = prepare_image(test)
  62. model = load_model(model_path)
  63.  
  64. # fmodel=foolbox.models. (model, bounds=(-1, 1))
  65. fmodel = KerasModel(model, bounds=(-1,1), predicts="logits")
  66. label=225
  67. attack=LBFGSAttack(fmodel,TargetClass(31))
  68. test=attack(test,label,unpack=True)
  69.  
  70. img = array_to_img(test)
  71. img.save(img_res_path)
  72.  
  73.  
  74. # In[27]:
  75.  
  76.  
  77. create_img("./trixi.png", "./trixi_frog.png", "./model.h5", TREE_FROG_STR, TREE_FROG_IDX)
  78. assert is_similar_img("./trixi.png", "./trixi_frog.png")
  79. print ("done")
  80.  
  81.  
  82. # In[ ]:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement