|
|
import torch |
|
|
from yolov5 import YOLOv5 |
|
|
from art.attacks.evasion import FastGradientMethod |
|
|
from art.estimators.classification import PyTorchClassifier |
|
|
from PIL import Image |
|
|
import numpy as np |
|
|
import matplotlib.pyplot as plt |
|
|
|
|
|
|
|
|
model = YOLOv5('yolov5s.pt', device='cuda') |
|
|
|
|
|
|
|
|
image_path = 'caminho/para/imagem.jpg' |
|
|
img = Image.open(image_path).convert('RGB') |
|
|
img = np.array(img) |
|
|
|
|
|
|
|
|
img_tensor = torch.from_numpy(img).float() / 255.0 |
|
|
img_tensor = img_tensor.permute(2, 0, 1).unsqueeze(0).cuda() |
|
|
|
|
|
|
|
|
results = model(img) |
|
|
results.show() |
|
|
|
|
|
|
|
|
def predict_fn(x): |
|
|
|
|
|
with torch.no_grad(): |
|
|
return model(x).xywh[0][:, 4].cpu().numpy() |
|
|
|
|
|
|
|
|
classifier = PyTorchClassifier( |
|
|
model=model.model, |
|
|
loss_fn=torch.nn.CrossEntropyLoss(), |
|
|
input_shape=(3, 640, 640), |
|
|
nb_classes=80, |
|
|
clip_values=(0, 1), |
|
|
preprocessing=(0, 1) |
|
|
) |
|
|
|
|
|
|
|
|
attack = FastGradientMethod(estimator=classifier, eps=0.1) |
|
|
adv_img = attack.generate(x=img_tensor.cpu().numpy()) |
|
|
|
|
|
|
|
|
adv_img = np.moveaxis(adv_img[0], 0, -1) |
|
|
adv_img = np.clip(adv_img * 255, 0, 255).astype(np.uint8) |
|
|
|
|
|
|
|
|
plt.imshow(adv_img) |
|
|
plt.title('Imagem Adversarial') |
|
|
plt.show() |
|
|
|
|
|
|
|
|
adv_results = model(adv_img) |
|
|
adv_results.show() |