FGSM方法生成交通信号牌的对抗图像样本

news2025/2/25 18:38:32

背景:

生成对抗样本,即扰动图像,让原本是“停车”的信号牌识别为“禁止驶入”

实验准备

模型:找一个训练好的,识别交通信号牌的CNN模型,灰度图像

模型地址:GitHub - Daulettulegenov/TSR_CNN: Traffic sign recognition

数据:Chinese Traffic Sign Database(CTSDB)

当下最受欢迎的国内交通标志数据集之一,该数据集容纳6164个交通标志图像,其中有58类交通标志。图像分为4170张图像的训练数据库和包含1994张图像的测试数据库两个子交通标志数据库。

官网链接:Traffic Sign Recogntion Database

数据结构: 

  • 模型在TSR_CNN-main下 
  • 8张目标表图像在 target下 
  • stop下是停止图像
  • no_entry下是禁止通行图像

对抗攻击

1、对抗步骤:

  1. 加载CNN模型
  2. 预测原始的输出类型,可以看到并不能正确的分类,因为是中文字幕“停”而不是 STOP。
  3. 需要迁移训练,让其识别中文的“停”
  4. 测试是否可以识别中文的停
  5. 预测新的输出类型,可以看到能正确的分类,即便是中文的“停”
  6. 生成扰动图像,原始图像增加扰动,让其能识别识别为no entry
  7. 保存扰动图像

2、代码如下:

ART-Adversarial Robustness Toolbox检测AI模型及对抗攻击的工具

import os
import cv2
import numpy as np
import tensorflow as tf
from art.estimators.classification import TensorFlowV2Classifier
from art.attacks.evasion import FastGradientMethod
from tensorflow.keras.models import load_model
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split

ID_CLASS_MAP = {
    0: 'Speed Limit 20 km/h',
    1: 'Speed Limit 30 km/h',
    2: 'Speed Limit 50 km/h',
    3: 'Speed Limit 60 km/h',
    4: 'Speed Limit 70 km/h',
    5: 'Speed Limit 80 km/h',
    6: 'End of Speed Limit 80 km/h',
    7: 'Speed Limit 100 km/h',
    8: 'Speed Limit 120 km/h',
    9: 'No passing',
    10: 'No passing for vechiles over 3.5 metric tons',
    11: 'Right-of-way at the next intersection',
    12: 'Priority road',
    13: 'Yield',
    14: 'Stop',
    15: 'No vechiles',
    16: 'Vechiles over 3.5 metric tons prohibited',
    17: 'No entry',
    18: 'General caution',
    19: 'Dangerous curve to the left',
    20: 'Dangerous curve to the right',
    21: 'Double curve',
    22: 'Bumpy road',
    23: 'Slippery road',
    24: 'Road narrows on the right',
    25: 'Road work',
    26: 'Traffic signals',
    27: 'Pedestrians',
    28: 'Children crossing',
    29: 'Bicycles crossing',
    30: 'Beware of ice/snow',
    31: 'Wild animals crossing',
    32: 'End of all speed and passing limits',
    33: 'Turn right ahead',
    34: 'Turn left ahead',
    35: 'Ahead only',
    36: 'Go straight or right',
    37: 'Go straight or left',
    38: 'Keep right',
    39: 'Keep left',
    40: 'Roundabout mandatory',
    41: 'End of no passing',
    42: 'End of no passing by vechiles over 3.5 metric tons'
}


def get_class_name(class_no):
    """
    根据类别编号返回对应的交通信号牌的名称
    :param class_no: 类别编号
    :return: 交通信号牌的名称
    """
    return ID_CLASS_MAP.get(class_no)


def grayscale(img):
    """
    将图像转换为灰度图像
    """
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return img


def equalize(img):
    """
    进行直方图均衡化
    """
    new_img = cv2.equalizeHist(img)
    return new_img


def preprocessing(img):
    """
    归一化处理
    """
    img = equalize(img)
    img = img / 255
    return img


def read_imgs(image_dir, label=0):
    """
    读取图片
    :param image_dir:
    :param label:
    :return:
    """
    image_files = os.listdir(image_dir)
    images = []
    labels = []
    for image_file in image_files:
        image_path = os.path.join(image_dir, image_file)
        image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)  # 以灰度模式读取图片
        image = cv2.resize(image, (30, 30))
        img = preprocessing(image)
        images.append(img)
        labels.append(label)
    return images, labels


def my_predict(model):
    """
    读取指定目录下的所有图像,然后使用模型进行预测,并打印出预测结果。
    """
    print('************my_predict*************')
    # 读取图片
    image_dir = r'D:\MyPython\adversarial\target'
    image_files = os.listdir(image_dir)
    images = []
    for image_file in image_files:
        image_path = os.path.join(image_dir, image_file)
        image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)  # 以灰度模式读取图片
        image = cv2.resize(image, (30, 30))
        img = preprocessing(image)
        img = img.reshape(1, 30, 30, 1)
        images.append(img)
        # PREDICT IMAGE
        predictions = model.predict(img)
        predict_x = model.predict(img)
        classIndex = np.argmax(predict_x)
        probabilityValue = np.amax(predictions)
        print("img path:", image_file, " ==> ", str(classIndex) + " " + str(get_class_name(classIndex)))
        print(str(round(probabilityValue * 100, 2)) + "%")


def reset_model(model):
    """
    修改模型的结构,移除最后的分类层,然后添加一个新的分类层。
    """
    base_model = model
    # 移除最后的分类层
    base_model = Model(inputs=base_model.input, outputs=base_model.layers[-2].output)
    # 添加一个新的分类层
    output = Dense(2, activation='softmax', name='new_dense')(base_model.output)
    model = Model(inputs=base_model.input, outputs=output)
    # 编译模型
    model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
    return model


def retrain_with2label(model):
    """
    取两个目录下的所有图像,然后使用这些图像和对应的标签来训练模型。
    """
    print('************retrain_with2label*************')
    image_dir1 = r'D:\MyPython\adversarial\stop'
    image_dir2 = r'D:\MyPython\adversarial\no_entry'
    images1, labels1 = read_imgs(image_dir1, 0)
    images2, labels2 = read_imgs(image_dir2, 1)

    # 合并图片和标签
    images = images1 + images2
    labels = labels1 + labels2

    images = np.array(images, dtype='float32')
    # 如果模型的输入形状是(30, 30, 1),那么我们需要增加一个维度
    if model.input_shape[-1] == 1:
        images = np.expand_dims(images, axis=-1)

    labels = np.array(labels)
    labels = to_categorical(labels, num_classes=2)

    # 划分训练集和测试集
    train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=0.2)
    # 训练模型
    model.fit(train_images, train_labels, validation_data=(test_images, test_labels), epochs=10)


def my_predict2(model):
    """
    读取指定目录下的所有图像,然后使用模型进行预测,并返回预测结果和图像数据。
    """
    # 选择stop的图像,扰动前的
    images, _ = read_imgs(r'D:\MyPython\adversarial\target')
    if model.input_shape[-1] == 1:
        images = np.expand_dims(images, axis=-1)
    preds = model.predict(images)
    print('Predicted before:', preds.argmax(axis=1))
    return images


def run_art(images):
    """
    使用对抗性攻击来生成对抗样本,并保存对抗样本和平均扰动。
    """
    # 创建一个目标标签(我们希望模型将0 stop识别为1 no entry)
    target_label = to_categorical(1, num_classes=2)
    target_label = np.tile(target_label, (len(images), 1))

    # 创建ART分类器
    classifier = TensorFlowV2Classifier(
        model=model,
        nb_classes=2,
        input_shape=(30, 30, 1),
        loss_object=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
        clip_values=(0, 1)
    )
    # 创建FGSM实例
    attack = FastGradientMethod(estimator=classifier, targeted=True)

    # 初始化对抗样本为原始图像
    adv_images = np.copy(images)

    for i in range(100):  # 最多迭代100次
        # 生成对抗样本的扰动
        perturbations = attack.generate(x=adv_images, y=target_label) - adv_images

        # 计算所有样本的平均扰动
        avg_perturbation = np.mean(perturbations, axis=0)

        # 将平均扰动添加到所有对抗样本上
        adv_images += avg_perturbation

        # 使用模型对对抗样本进行预测
        preds = model.predict(adv_images)
        print('Iteration:', i, 'Predicted after:', preds.argmax(axis=1))

        # 如果所有的预测结果都为1,那么停止迭代
        if np.all(preds.argmax(axis=1) == 1):
            break

    # 保存对抗样本
    for i in range(len(adv_images)):
        # 将图像的数据类型转换为uint8,并且将图像的值范围调整到[0, 255]
        img = (adv_images[i] * 255).astype(np.uint8)
        # 保存图像
        print(f'save adversarial picture: adversarial_image_{i}.png')
        cv2.imwrite(f'adversarial_image_{i}.png', img)

    # 归一化平均扰动并保存为图像
    avg_perturbation = (avg_perturbation - np.min(avg_perturbation)) / (
                np.max(avg_perturbation) - np.min(avg_perturbation))
    # 将平均扰动的值范围调整到[0, 255],并转换为uint8类型
    avg_perturbation = (avg_perturbation * 255).astype(np.uint8)
    # 将灰度图像转换为RGB图像
    avg_perturbation_rgb = cv2.cvtColor(avg_perturbation, cv2.COLOR_GRAY2RGB)
    # 保存图像
    print(f'save perturbation picture: perturbation_image.png')
    cv2.imwrite('perturbation_image.png', avg_perturbation_rgb)


if __name__ == "__main__":
    # 加载CNN模型
    model = load_model(r'D:\MyPython\adversarial\TSR_CNN-main\CNN_model_3.h5', compile=False)
    # 预测原始的输出类型,可以看到并不能正确的分类,因为是中文字幕“停”而不是 STOP。
    my_predict(model)
    # 需要迁移训练,让其识别中文的“停”
    model = reset_model(model)
    # 测试是否可以识别中文的停
    retrain_with2label(model)
    # 预测新的输出类型,可以看到能正确的分类,即便是中文的“停”
    images = my_predict2(model)
    # 生成扰动图像,原始图像增加扰动,让其能识别识别为no entry,保存扰动图像
    run_art(images)

3、实验结果:

3.1运行日志

************my_predict*************
img path: 052_0001_j.png  ==>  28 Children crossing
99.83%
img path: 052_0005_j.png  ==>  3 Speed Limit 60 km/h
50.46%
img path: 052_0011.png  ==>  3 Speed Limit 60 km/h
52.22%
img path: 052_0013.png  ==>  8 Speed Limit 120 km/h
93.85%
img path: 052_1_0002_1_j.png  ==>  35 Ahead only
26.76%
img path: capture_20240114141426681.bmp  ==>  40 Roundabout mandatory
89.58%
img path: capture_20240114141515221.bmp  ==>  17 No entry
34.44%
img path: capture_20240114141530130.bmp  ==>  33 Turn right ahead
42.66%
************retrain_with2label*************
Epoch 1/10
3/3 [==============================] - 1s 107ms/step - loss: 1.2774 - accuracy: 0.4857 - val_loss: 0.2057 - val_accuracy: 1.0000
Epoch 2/10
3/3 [==============================] - 0s 32ms/step - loss: 0.2968 - accuracy: 0.8714 - val_loss: 0.1363 - val_accuracy: 1.0000
Epoch 3/10
3/3 [==============================] - 0s 33ms/step - loss: 0.1908 - accuracy: 0.9286 - val_loss: 0.1200 - val_accuracy: 1.0000
Epoch 4/10
3/3 [==============================] - 0s 31ms/step - loss: 0.1482 - accuracy: 0.9429 - val_loss: 0.1365 - val_accuracy: 1.0000
Epoch 5/10
3/3 [==============================] - 0s 31ms/step - loss: 0.0665 - accuracy: 1.0000 - val_loss: 0.1404 - val_accuracy: 1.0000
Epoch 6/10
3/3 [==============================] - 0s 32ms/step - loss: 0.0638 - accuracy: 0.9857 - val_loss: 0.1384 - val_accuracy: 1.0000
Epoch 7/10
3/3 [==============================] - 0s 31ms/step - loss: 0.0347 - accuracy: 0.9857 - val_loss: 0.1278 - val_accuracy: 1.0000
Epoch 8/10
3/3 [==============================] - 0s 30ms/step - loss: 0.0228 - accuracy: 0.9857 - val_loss: 0.1143 - val_accuracy: 0.8889
Epoch 9/10
3/3 [==============================] - 0s 32ms/step - loss: 0.0056 - accuracy: 1.0000 - val_loss: 0.1030 - val_accuracy: 0.8889
Epoch 10/10
3/3 [==============================] - 0s 32ms/step - loss: 0.0112 - accuracy: 1.0000 - val_loss: 0.0898 - val_accuracy: 0.8889
Predicted before: [0 0 0 0 0 0 0 0]
Iteration: 0 Predicted after: [0 0 0 0 1 1 0 0]
Iteration: 1 Predicted after: [1 1 1 1 1 1 1 1]
save adversarial picture: adversarial_image_0.png
save adversarial picture: adversarial_image_1.png
save adversarial picture: adversarial_image_2.png
save adversarial picture: adversarial_image_3.png
save adversarial picture: adversarial_image_4.png
save adversarial picture: adversarial_image_5.png
save adversarial picture: adversarial_image_6.png
save adversarial picture: adversarial_image_7.png
save perturbation picture: perturbation_image.png

3.2 结果分析

通过以上日志可知,迭代了两轮后,预测由“停”字标签==>变成了“禁止”标签

8张目标图像+扰动后的对抗图像如下,依稀可见“停”字:

对抗扰动 如下:


 参考:

https://www.cnblogs.com/bonelee/p/17797484.html

国内外交通标志数据集 - 知乎

Keras导入自定义metric模型报错: unknown metric function: Please ensure this object is passed to`custom_object‘_自定义的metric不被调用-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1383143.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

高级RAG(六): 句子-窗口检索

之前我们介绍了LlamaIndex的从小到大的检索 的检索方法,今天我们再来介绍llamaindex的另外一种高级检索方法: 句子-窗口检索(Sentence Window Retrieval),在开始介绍之前让我们先回顾一下基本的RAG检索的流程,如下图所示: 在执行基…

学会编写自定义configure脚本,轻松实现定制化配置

学会编写自定义configure脚本,轻松实现定制化配置 一、configure脚本的作用和重要性二、configure脚本的基本结构和语法三、编写自定义configure脚本的步骤四、示例五、常见的问题总结 一、configure脚本的作用和重要性 configure脚本是用于自动配置软件源代码的脚…

jmeter如何做接口测试?

Jmeter介绍&测试准备: Jmeter介绍:Jmeter是软件行业里面比较常用的接口、性能测试工具,下面介绍下如何用Jmeter做接口测试以及如何用它连接MySQL数据库。 前期准备:测试前,需要安装好Jmeter以及jdk并配置好jdk环…

高级JavaScript。同步和异步,阻塞和非阻塞

同步阻塞 同步非阻塞 异步阻塞 异步非阻塞 在当什么是同步和异步,阻塞与非阻塞的概念还没弄清楚之前,更别提上面这些组合术语了,只会让你更加困惑。 同步和异步 同步和异步其实指的是,请求发起方对消息结果的获取是主动发起…

强化学习应用(五):基于Q-learning算法的无人车配送路径规划(通过Python代码)

一、Q-learning算法介绍 Q-learning是一种强化学习算法,用于解决基于环境的决策问题。它通过学习一个Q-table来指导智能体在不同状态下采取最优动作。下面是Q-learning算法的基本步骤: 1. 定义环境:确定问题的状态和动作空间,并…

NI PXIe-6386国产替代,8路AI(16位,14 MS/s/ch),2路A​O,24路DIO,PXI多功能I/O模块

PXIe-6386 PXIe,8路AI(16位,14 MS/s/ch),2路A​O,24路DIO,PXI多功能I/O模块 PXIe-6386是一款同步采样的多功能DAQ设备。该模块提供了模拟 I/O、数字I/O、四个32位计数器和模拟和数字触发。板载N…

2024年【G1工业锅炉司炉】考试及G1工业锅炉司炉考试资料

题库来源:安全生产模拟考试一点通公众号小程序 G1工业锅炉司炉考试根据新G1工业锅炉司炉考试大纲要求,安全生产模拟考试一点通将G1工业锅炉司炉模拟考试试题进行汇编,组成一套G1工业锅炉司炉全真模拟考试试题,学员可通过G1工业锅…

【现代密码学】笔记3.1-3.3 --规约证明、伪随机性《introduction to modern cryphtography》

【现代密码学】笔记3.1-3.3 --规约证明、伪随机性《introduction to modern cryphtography》 写在最前面私钥加密与伪随机性 第一部分密码学的计算方法论计算安全加密的定义:对称加密算法 伪随机性伪随机生成器(PRG) 规约法规约证明 构造安全…

LeetCode刷题.15(哈希表与计数排序解决41. 缺失的第一个正数)

给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。 请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。 示例 1: 输入:nums [1,2,0] 输出:3 示例 2: 输入:nums …

MCS-51---串行通信的特点

目录 一.同步通信和异步通信 1.异步通信 2.同步通信 二.串行通信的方式 1.单工 2.半双工 3.全双工 三.串行通信的速率 四.MCS-51单片机结构 五.串行口的控制 1.串行口控制寄存器(SCON) 2.电源控制寄存器(PCON) 六.波特率的设计 七.串行口的工作方式 1.方式0 2.…

NLP论文阅读记录 - WOS | ROUGE-SEM:使用ROUGE结合语义更好地评估摘要

文章目录 前言0、论文摘要一、Introduction1.1目标问题1.2相关的尝试1.3本文贡献 二.相关工作三.本文方法四 实验效果4.1数据集4.2 对比模型4.3实施细节4.4评估指标4.5 实验结果4.6 细粒度分析 五 总结 前言 ROUGE-SEM: Better evaluation of summarization using ROUGE combin…

操作系统详解(5.1)——信号(Signal)的相关题目

系列文章: 操作系统详解(1)——操作系统的作用 操作系统详解(2)——异常处理(Exception) 操作系统详解(3)——进程、并发和并行 操作系统详解(4)——进程控制(fork, waitpid, sleep, execve) 操作系统详解(5)——信号(Signal) 文章目录 题目第一问第二问第三问 题目…

python24.1.14while循环

当条件结束时间未知时,while循环比for循环更合适 实践

Debian(Linux)局域网共享文件-NFS

NFS (Network File system) 是一种客户端-服务器文件系统协议,允许多个系统或用户访问相同的共享文件夹或文件。最新版本是 NFS-V4,共享文件就像存储在本地一样。它提供了中央管理,可以使用防火墙和 Kerberos 身份验证进行保护。 本文将指导…

docker-compose部署kafka、SASL模式(密码校验模式)

一.基础kafka部署 zookeeper,kafka,kafka-ui docker-compose.yml 注意点:192.168.1.20 是宿主机的ip version: "3" services:zookeeper:image: wurstmeister/zookeepercontainer_name: zookeeperrestart: alwaysports:- 2181:2…

未来的失业将是常态吗?

2024年,科技巨头谷歌、亚马逊都在本周宣布大规模裁员,影响到众多部门。此外,社交平台 Discord 表示将裁员 17%,游戏服务商 Unity Software 宣布将裁员 25%,语言学习应用程序 Duolingo 则称解雇了 10% 的正式职工&#…

使用 rosdep 管理依赖关系

什么是rosdep? rosdep是 ROS 的依赖管理实用程序,可以与 ROS 包和外部库一起使用。 是一个命令行实用工具,用于标识和安装依赖项以生成或安装包。 在以下情况下,可以调用或调用它:rosdep 构建工作区并需要适当的依赖项…

关于CodeReview的一些实践和思考

在日常开发中,Code Review 的重要性日益凸显。它不仅有助于提升代码质量,还促进了团队成员之间的知识共享和技能提升。本文将主要聚焦于 Code Review,分享在这个过程中的一些心得和思考。 CodeReview常用到的一些术语 之前看到公司的大佬经…

ssm基于Java的众惠商城的设计与实现论文

摘 要 如今社会上各行各业,都喜欢用自己行业的专属软件工作,互联网发展到这个时候,人们已经发现离不开了互联网。新技术的产生,往往能解决一些老技术的弊端问题。因为传统用户购物信息管理难度大,容错率低&#xff0c…

Python基础知识:整理14 利用pyecharts生成地图

1 地图可视化的基本使用 from pyecharts.charts import Map from pyecharts.options import VisualMapOpts # 准备地图对象 map Map()# 准备数据 data [("北京市", 8), ("上海市", 99), ("广州省", 199), ("重庆市", 400), ("…