# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import numpy as np import matplotlib.image as mp from mindspore import context, Tensor import mindspore from mindspore.dataset.vision.py_transforms import ToTensor import mindspore.dataset.vision.py_transforms as P from mindspore.dataset.vision.py_transforms import ToPIL as ToPILImage from FaceRecognition.eval import get_net import AFR context.set_context(mode=context.GRAPH_MODE, device_target="GPU") imageize = ToPILImage() if __name__ == '__main__': """ The input image, target image and adversarial image are tested using the FaceRecognition model. """ image = AFR.load_data('opencv_photo/adv_input') inputs = AFR.load_data('opencv_photo/input/') targets = AFR.load_data('opencv_photo/target/') tensorize = ToTensor() normalize = P.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) expand_dims = mindspore.ops.ExpandDims() MEAN = Tensor([0.485, 0.456, 0.406]) STD = Tensor([0.229, 0.224, 0.225]) resnet = get_net() image = mp.imread("./对抗图像.jpg") adv = Tensor(normalize(tensorize(image))) input_tensor = Tensor(normalize(tensorize(inputs[0]))) target_tensor = Tensor(normalize(tensorize(targets[0]))) adversarial_emb = resnet(expand_dims(adv, 0)) input_emb = resnet(expand_dims(input_tensor, 0)) target_emb = resnet(expand_dims(target_tensor, 0)) adversarial = np.argmax(adversarial_emb.asnumpy()) target = np.argmax(target_emb.asnumpy()) input = np.argmax(input_emb.asnumpy()) print("input:", input) print("input_confidence:", input_emb.asnumpy()[0][input]) print("================================") print("adversarial:", adversarial) print("adversarial_confidence:", adversarial_emb.asnumpy()[0][adversarial]) print("Confidence changes for input:", adversarial_emb.asnumpy()[0][input]) print("================================") print("input:%d, target:%d, adversarial:%d" % (input, target, adversarial))