#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import keras
import numpy as np
import foolbox
from keras.models import load_model
from PIL import Image
import json
from foolbox.criteria import TargetClassProbability
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
#攻击函数
def start_attack(foolmodel, label , pixel):
attack=foolbox.attacks.SinglePixelAttack(foolmodel)
adv=attack(image.reshape(28,28,-1) ,label , unpack = True, max_pixels=pixel)
#返回生成的攻击样本,用于保存
return adv
if __name__=='__main__':
keras.backend.set_learning_phase(0)
model=load_model('./Model_keras/mnist/model.hdf5')
foolmodel=foolbox.models.KerasModel(model,bounds=(0,1),preprocessing=(0,1))
image=Image.open('original.jpg')
image=np.array(image)
image=image.astype(np.float)
image/=255
if len(image.shape) == 3:
image = image[:,:,0]
pred_test=np.argmax(model.predict(image.reshape(-1,28,28,1)),axis=1)
label=pred_test[0]
print(label)
#请在此修改参数的值,展开对模型的攻击
#r:float
#Perturbation parameter that controls the cyclic perturbation; must be in [0, 2]
#p:float
#Perturbation parameter that controls the pixel sensitivity estimation
#d:int
#The half side length of the neighborhood square
#t:int
#The number of pixels perturbed at each round
#R:int
#An upper bound on the number of iterations
#建议R的取值范围[0,200]
adv = start_attack(foolmodel,label ,100)
plt.imshow(adv.reshape(28,28))
plt.imsave('adversial.jpg',adv.reshape(28,28),format="jpg",cmap='gray')