Create code.py
Browse files
code.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from yolov5 import YOLOv5
|
| 3 |
+
from art.attacks.evasion import FastGradientMethod
|
| 4 |
+
from art.classifiers import PyTorchClassifier
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import numpy as np
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
|
| 9 |
+
# Carregar o modelo YOLOv5
|
| 10 |
+
model = YOLOv5('yolov5s.pt', device='cuda') # Use yolov5s.pt ou outro modelo
|
| 11 |
+
|
| 12 |
+
# Carregar uma imagem de exemplo
|
| 13 |
+
image_path = 'caminho/para/imagem.jpg' # Substitua pelo caminho correto
|
| 14 |
+
img = Image.open(image_path).convert('RGB')
|
| 15 |
+
img = np.array(img) # Converter para array numpy
|
| 16 |
+
|
| 17 |
+
# Preparar a imagem para o modelo
|
| 18 |
+
img_tensor = torch.from_numpy(img).float() / 255.0
|
| 19 |
+
img_tensor = img_tensor.permute(2, 0, 1).unsqueeze(0).cuda() # Adicionar batch e mover para GPU
|
| 20 |
+
|
| 21 |
+
# Fazer a detecção normal
|
| 22 |
+
results = model(img)
|
| 23 |
+
results.show()
|
| 24 |
+
|
| 25 |
+
# Criar o classificador PyTorch para ART
|
| 26 |
+
def predict_fn(x):
|
| 27 |
+
# Função de predição para ART
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
return model(x).xywh[0][:, 4].cpu().numpy() # Retorna as probabilidades de deteção de objetos
|
| 30 |
+
|
| 31 |
+
classifier = PyTorchClassifier(
|
| 32 |
+
model=model.model, # Passando o modelo YOLO para ART
|
| 33 |
+
loss_fn=torch.nn.CrossEntropyLoss(),
|
| 34 |
+
input_shape=(3, 640, 640), # YOLOv5 trabalha com imagens de 640x640
|
| 35 |
+
nb_classes=80, # 80 classes do COCO dataset
|
| 36 |
+
clip_values=(0, 1), # Normalização das imagens
|
| 37 |
+
preprocessing=(0, 1)
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Criar o ataque adversarial com o ART (exemplo com FGSM)
|
| 41 |
+
attack = FastGradientMethod(estimator=classifier, eps=0.1) # eps controla a intensidade do ataque
|
| 42 |
+
adv_img = attack.generate(x=img_tensor.cpu().numpy())
|
| 43 |
+
|
| 44 |
+
# Converter a imagem adversarial para um formato visualizável
|
| 45 |
+
adv_img = np.moveaxis(adv_img[0], 0, -1) # Move as dimensões para (H, W, C)
|
| 46 |
+
adv_img = np.clip(adv_img * 255, 0, 255).astype(np.uint8)
|
| 47 |
+
|
| 48 |
+
# Mostrar a imagem adversarial
|
| 49 |
+
plt.imshow(adv_img)
|
| 50 |
+
plt.title('Imagem Adversarial')
|
| 51 |
+
plt.show()
|
| 52 |
+
|
| 53 |
+
# Aplicar o modelo YOLO na imagem adversarial
|
| 54 |
+
adv_results = model(adv_img)
|
| 55 |
+
adv_results.show()
|