def get(self): data = self.parser.parse_args() img = data.get('img') img_data = img.split(',') img = np.array(img_data, np.float32).reshape(28, 28) img = img * 255.0 img_new = np.zeros((1, 32, 32, 1)) img_new[0] = np.pad(img.reshape(28, 28), [(2, ), (2, )], mode='constant').reshape(32, 32, 1) global sess global graph with graph.as_default(): set_session(sess) attack = HopSkipJump(classifier=classifier, targeted=False, max_iter=0, max_eval=1000, init_eval=10) iter_step = 3 x_adv = None for i in range(iter_step): x_adv = attack.generate(x=img_new, x_adv_init=x_adv, resume=True) #clear_output() # print("Adversarial image at step %d." % (i * iter_step), # "and class label %d." % np.argmax(classifier.predict(x_adv)[0])) attack.max_iter = iter_step sav_img = Image.fromarray(x_adv.reshape(32, 32)) sav_img = sav_img.convert("L") sav_img.save("test.jpg") buffer = BytesIO() sav_img.save(buffer, format="JPEG") myimage = buffer.getvalue() res = str(predict(x_adv)) print("After Attack: ", res) return jsonify({ 'res': res, 'dat': bytes.decode(base64.b64encode(myimage)) })
attack = HopSkipJump(classifier=classifier, targeted=True, max_iter=0, max_eval=1000, init_eval=10) iter_step = 10 stop = Image.open(curr_path + "../danny-machine/machine.jpg") stop = np.array([np.array(stop)]).astype(float) x_adv = stop errors = [] for i in range(100): x_adv = attack.generate(x=np.array([target_image]), y=[1], x_adv_init=x_adv) l2_err = np.linalg.norm(np.reshape(x_adv[0] - target_image, [-1])) print("Adversarial image at step %d." % (i * iter_step), "L2 error", np.linalg.norm(np.reshape(x_adv[0] - target_image, [-1])), "and class label %d." % np.argmax(classifier.predict(x_adv)[0])) errors.append((i * iter_step, l2_err)) im = Image.fromarray(np.reshape(x_adv[0].astype(np.uint8), SHAPE)) im.save(curr_path + f"../danny-machine/step{i}.png") #plt.imshow(np.reshape(x_adv[0].astype(np.float32), (400, 400))) #plt.show(block=False) attack.max_iter = iter_step print(errors) open('errs.txt', 'r').write(str(errors))