前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于Aidlux的智慧交通AI安全车辆检测训练实战

基于Aidlux的智慧交通AI安全车辆检测训练实战

原创
作者头像
用户10249268
发布2022-12-06 21:19:07
3990
发布2022-12-06 21:19:07
举报
文章被收录于专栏:Aidlux,智慧安防

1、背景介绍

AI项目在不断落地的同时,也伴随着安全风险的日益增加,需要引起工业界的重视。以深度学习为核心的人工智能存在易受攻击的缺陷,攻击者通过精心制作的3D人脸面具以及相应的合成图片,破解了多个公司的人脸识别系统,说明人工智能的可靠性仍需加强。目前AI算法模型以黑盒为主,具备高度复杂性和不确定性,很多决策原理无法直观理解。

在智慧交通场景中,面对复杂的交通应用场景,AI算法也很容易受到一些人为的对抗样本攻击,以及复杂自然环境中引入的不确定噪声影响。比如车辆,行人人脸,车牌,交通指示牌等都可能成为受攻击的目标。加上智慧交通AI项目一般都是ToB或者ToG的,客户对项目底层技术的可解释性与数据安全有一定的要求。黑盒系统容易引发不确定性风险,很多交通事件以及交通违规判定仍需专业人员进行二次验证。此外,数据偏见在交通场景中尤为常见。

2、Aldlux使用操作流程

Aidlux介绍和使用流程,看可参考连接《智慧安防AI实战训练营:边缘端实现越界识别》Lesson2

2.1、测量检测检测模型的部署和操作,以及AI对抗与防御介绍理解,可参考这位大佬提供的课程连接,大白训练营Rocky老师课程

3、AI对抗攻击与防御算法简介

3.1、AI对抗攻击算法讲解

对抗攻击(adversarial attack)是AI安全方向的重要分支,其核心逻辑是在数据中增加一些微小扰 动,在人类视觉系统无法察觉的情况下,使得算法模型对这些数据产生误判。其中被增加扰动的数据 也称为对抗样本。比如下面添加噪声识别大熊猫案列,和下面人体检测中添加人体画像等,都会导致错误案列识别或识别不到。

详细常用AI对抗攻击算法可以参考Rocky老师讲解

目前主流对抗攻击算法的总体分支与逻辑如下:

白盒攻击:简单理解为算法模型参数和训练数据等信息被攻击着所掌握,了解模型运行方式。

黑盒攻击:简单理解为算法模型参数和数据攻击者并不知情,所进行的攻击为黑盒攻击。

3.1.1对抗攻击算法实现:

注意修改读取的文件路径img_path。文件attack_code.py

代码语言:javascript
复制
import os
import torch
import torch.nn as nn
from torchvision.models import mobilenet_v2
from advertorch.utils import predict_from_logits
from advertorch.utils import NormalizeByChannelMeanStd
from advertorch.attacks import LinfPGDAttack
from advertorch_examples.utils import ImageNetClassNameLookup
from advertorch_examples.utils import bhwc2bchw
from advertorch_examples.utils import bchw2bhwc
device = "cuda" if torch.cuda.is_available() else "cpu"

### 读取图片
def get_image():
    img_path = os.path.join("E:/Aidlux/2/Lesson4_code/Lesson4_code/adv_code/images", "school_bus.png")
    img_url = "https://farm1.static.flickr.com/230/524562325_fb0a11d1e1.jpg"

    def _load_image():
        from skimage.io import imread
        return imread(img_path) / 255。

    if os.path.exists(img_path):
        return _load_image()
    else:
        import urllib
        urllib.request.urlretrieve(img_url, img_path)
        return _load_image()

def tensor2npimg(tensor):
    return bchw2bhwc(tensor[0].cpu().numpy())

### 展示攻击结果
def show_images(model, img, advimg, enhance=127):
    np_advimg = tensor2npimg(advimg)
    np_perturb = tensor2npimg(advimg - img)

    pred = imagenet_label2classname(predict_from_logits(model(img)))
    advpred = imagenet_label2classname(predict_from_logits(model(advimg)))

    import matplotlib.pyplot as plt

    plt.figure(figsize=(10, 5))
    plt.subplot(1, 3, 1)
    plt.imshow(np_img)

    plt.axis("off")
    plt.title("original image\n prediction: {}".format(pred))
    plt.subplot(1, 3, 2)
    plt.imshow(np_perturb * enhance + 0.5)

    plt.axis("off")
    plt.title("the perturbation,\n enhanced {} times".format(enhance))
    plt.subplot(1, 3, 3)
    plt.imshow(np_advimg)
    plt.axis("off")
    plt.title("perturbed image\n prediction: {}".format(advpred))
    plt.show()

normalize = NormalizeByChannelMeanStd(
    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

### 常规模型加载
model = mobilenet_v2(pretrained=True)
model.eval()
model = nn.Sequential(normalize, model)
model = model.to(device)

### 数据预处理
np_img = get_image()
img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)
imagenet_label2classname = ImageNetClassNameLookup()

### 测试模型输出结果
pred = imagenet_label2classname(predict_from_logits(model(img)))
print("test output:", pred)

### 输出原label
pred_label = predict_from_logits(model(img))

### 对抗攻击:PGD攻击算法
adversary = LinfPGDAttack(
    model, eps=8 / 255, eps_iter=2 / 255, nb_iter=80,
    rand_init=True)
 
### 完成攻击,输出对抗样本
advimg = adversary.perturb(img, pred_label)

### 展示源图片,对抗扰动,对抗样本以及模型的输出结果
show_images(model, img, advimg)

取得school_bus进行对抗后生成了acoustic_gutar的错误标签。

车辆检测提取出来的cab识别成了slot

3.2、AI安全防御算法讲解

在智慧交通场景中,常用的对抗防御方法有与对抗攻击结合紧密的AI业务的鲁棒性与安全性检查工具;研究对抗攻击,来增强对实际场景中受到的攻击情形的判断力;使用对抗攻击对敏感信息进行隐藏;使用对抗样本在模型训练过程中进行对抗训练。 由于智慧交通场景的算法解决方案对耗时和内存占用有较高的要求,所以防御预处理与防御后处理作为常规防御的首要选择。 同时,针对可能存在的安全风险,在开发阶段,设计鲁棒性的模型结构,提升算法解决方案的整体安全性。 或者训练轻量级的对抗攻击检测模型,作为算法解决方案的安全模块,在受到攻击风险时,启动防御算法功能。

防御算法划分:目前主流对抗防御的总体分支与逻辑如上图右。

3.2.1对抗防御算法实现:

注意生成的对抗图片路径img_path,文件defense_code.py

代码语言:javascript
复制
import os
import torch
import torch.nn as nn
from torchvision.models import mobilenet_v2
from advertorch.utils import predict_from_logits
from advertorch.utils import NormalizeByChannelMeanStd
from robust_layer import GradientConcealment, ResizedPaddingLayer
from advertorch.attacks import LinfPGDAttack
from advertorch_examples.utils import ImageNetClassNameLookup
from advertorch_examples.utils import bhwc2bchw
from advertorch_examples.utils import bchw2bhwc

device = "cuda" if torch.cuda.is_available() else "cpu"

### 读取图片
def get_image():
    img_path = os.path.join("E:/Aidlux/2/Lesson4_code/Lesson4_code/adv_code/images", "school_bus.png")
    img_url = "https://farm1.static.flickr.com/230/524562325_fb0a11d1e1.jpg"

    def _load_image():
        from skimage.io import imread
        return imread(img_path) / 255.

    if os.path.exists(img_path):
        return _load_image()
    else:
        import urllib
        urllib.request.urlretrieve(img_url, img_path)
        return _load_image()

def tensor2npimg(tensor):
    return bchw2bhwc(tensor[0].cpu().numpy())

### 展示攻击结果
def show_images(model, img, advimg, enhance=127):
    np_advimg = tensor2npimg(advimg)
    np_perturb = tensor2npimg(advimg - img)

    pred = imagenet_label2classname(predict_from_logits(model(img)))
    advpred = imagenet_label2classname(predict_from_logits(model(advimg)))

    import matplotlib.pyplot as plt

    plt.figure(figsize=(10, 5))
    plt.subplot(1, 3, 1)
    plt.imshow(np_img)

    plt.axis("off")
    plt.title("original image\n prediction: {}".format(pred))
    plt.subplot(1, 3, 2)
    plt.imshow(np_perturb * enhance + 0.5)

    plt.axis("off")
    plt.title("the perturbation,\n enhanced {} times".format(enhance))
    plt.subplot(1, 3, 3)
    plt.imshow(np_advimg)
    plt.axis("off")
    plt.title("perturbed image\n prediction: {}".format(advpred))
    plt.show()

normalize = NormalizeByChannelMeanStd(
    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

### GCM模块
robust_mode = GradientConcealment()

### 常规模型+GCM模块
class Model(nn.Module):
    def __init__(self, l=290):
        super(Model, self).__init__()

        self.l = l
        self.gcm = GradientConcealment()
        # model = resnet18(pretrained=True)
        model = mobilenet_v2(pretrained=True)

        # pth_path = "/Users/rocky/Desktop/训练营/model/mobilenet_v2-b0353104.pth"
        # print(f'Loading pth from {pth_path}')
        # state_dict = torch.load(pth_path, map_location='cpu')
        # is_strict = False
        # if 'model' in state_dict.keys():
        #    model.load_state_dict(state_dict['model'], strict=is_strict)
        # else:
        #    model.load_state_dict(state_dict, strict=is_strict)

        normalize = NormalizeByChannelMeanStd(
            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        self.model = nn.Sequential(normalize, model)

    def load_params(self):
        pass

    def forward(self, x):
        x = self.gcm(x)
        # x = ResizedPaddingLayer(self.l)(x)
        out = self.model(x)
        return out

### 常规模型+GCM模块 加载
model_defense = Model().eval().to(device)

### 数据预处理
np_img = get_image()
img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)
imagenet_label2classname = ImageNetClassNameLookup()

### 测试模型输出结果
pred_defense = imagenet_label2classname(predict_from_logits(model_defense(img)))
print("test output:", pred_defense)

pre_label = predict_from_logits(model_defense(img))

### 对抗攻击:PGD攻击算法
adversary = LinfPGDAttack(
    model_defense, eps=8 / 255, eps_iter=2 / 255, nb_iter=80,
    rand_init=True, targeted=False)

### 完成攻击,输出对抗样本
advimg = adversary.perturb(img, pre_label)

### 展示源图片,对抗扰动,对抗样本以及模型的输出结果
show_images(model_defense, img, advimg)

可以看到成功生成了正确的图片标签。

4、总体流程(车辆检测/检测框提取+对抗攻击+安全检测告警)

总体业务流程

4.1检测车辆特征提取

车辆特征提取代码如下,注意修改文件读取路径。

代码语言:javascript
复制
import cvs
import os
import time
import cv2
from cvs import *
import aidlite_gpu
from utils import detect_postprocess, preprocess_img, draw_detect_res, extract_detect_res


# AidLite初始化:调用AidLite进行AI模型的加载与推理,需导入aidlite
aidlite = aidlite_gpu.aidlite()
# Aidlite模型路径
model_path = '/home/Lesson5_code_2/yolov5_code/aidlux/yolov5_car_best-fp16.tflite'
# 定义输入输出shape
in_shape = [1 * 640 * 640 * 3 * 4]
out_shape = [1 * 25200 * 6 * 4]
# 加载Aidlite检测模型:支持tflite, tnn, mnn, ms, nb格式的模型加载
aidlite.ANNModel(model_path, in_shape, out_shape, 4, 0)

# 读取图片进行推理
# 设置测试集路径
source = "/home/Lesson5_code_2/adv_code/test_images"
images_list = os.listdir(source)
print(images_list)
frame_id = 0
# 读取数据集
for image_name in images_list:
    frame_id += 1
    print("frame_id:", frame_id)
    image_path = os.path.join(source, image_name)
    frame = cvs.imread(image_path)

    # 预处理
    img = preprocess_img(frame, target_shape=(640, 640), div_num=255, means=None, stds=None)
    # 数据转换:因为setTensor_Fp32()需要的是float32类型的数据,所以送入的input的数据需为float32,大多数的开发者都会忘记将图像的数据类型转换为float32
    aidlite.setInput_Float32(img, 640, 640)
    # 模型推理API
    aidlite.invoke()
    # 读取返回的结果
    pred = aidlite.getOutput_Float32(0)
    # 数据维度转换
    pred = pred.reshape(1, 25200, 6)[0]
    # 模型推理后处理
    pred = detect_postprocess(pred, frame.shape, [640, 640, 3], conf_thres=0.25, iou_thres=0.45)
    # 绘制推理结果
    res_img = draw_detect_res(frame, pred)
    # cvs.imshow(res_img)

    # 测试结果展示停顿
    #time.sleep(5)

    # 图片裁剪,提取车辆目标区域
    extract_detect_res(frame, pred, image_name)

    # cvs.imshow(cut_img)
    # cap.release()
    # cv2.destroyAllWindows()

4.2对抗样本生成

具体来说,上面我们已经将车辆目标区域提取出来,在实际AI项目中,攻击者一般难以获得算法模型的参数,白盒攻击难以展开。 这时,可以选择另外一个模型作为替身模型,比如我们知道他后面会进行车辆分类,但是不知道用的 什么分类模型(实际上系统方用的Mobilenetv2),这时我们可以使用一个已有的分类模型 (ResNet18)作为替身。 使用攻击算法对替身模型进行攻击,这样生成的车辆目标区域对抗样本一定程度上也会使得业务模型 产生错误的输出。

对抗攻击算法步骤为3.1算法实现过程,稍微进行输入图片的改写。

代码语言:javascript
复制
normalize = NormalizeByChannelMeanStd(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
imagenet_label2classname = ImageNetClassNameLookup()

### 常规模型加载
model = mobilenet_v2(pretrained=True)
model.eval()
model = nn.Sequential(normalize, model)
model = model.to(device)

### 替身模型加载
model_su = resnet18(pretrained=True)
model_su.eval()
model_su = nn.Sequential(normalize, model_su)
model_su = model_su.to(device)

Attack_flag = True  #判断是否进行攻击
model_detect = Model().eval().to(device)
model_detect_attack = Detect_Model().eval().to(device)

###对抗攻击部分
def PGD_Attack(model, model_su, img_input):
    ### 数据预处理
    np_img = img_input[:,:,::-1] / 255.0
    img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)
    imagenet_label2classname = ImageNetClassNameLookup()
    ### 测试模型输出结果
    pred = imagenet_label2classname(predict_from_logits(model(img)))
    print("test output:", pred)
    ### 输出原label
    pred_label = predict_from_logits(model_su(img))
    ### 对抗攻击:PGD攻击算法
    adversary = LinfPGDAttack(
        model_su, eps=8/255, eps_iter=2/255, nb_iter=80,
        rand_init=True, targeted=False)
    ### 完成攻击,输出对抗样本
    advimg = adversary.perturb(img, pred_label)     ##torch.Size([1, 3, 24, 42])
    return advimg

4.3攻击检测与安全警告

在前面的学习中,我们知道,对抗攻击监测模型是一个能够捕捉对抗扰动的二分类模型,监测模型的输入是一张图片,输出则是两个类别,0表示图片是正常图片,1表示图片是具有安全风险的图片。 本次训练营中,Rocky直接使用了一个已经训练好的基于ResNet50的模型,作为本次训练营的监测模型。

在实际场景中,当数据流中的图片进入AI项目中时,在一些关键节点处,可以前置一个监测模型,用于判断输入数据是否存在安全风险,如果发现对抗样本,则及时告警,并切断后续的算法功能,避免不确定风险的产生。

一般在实际场景的AI项目中,会出现一个告警弹窗,并且会告知安全人员及时进行安全排查。 当然我们此次训练营并没有业务系统,为了更加贴近实际,本次训练营采用一种简单的方式,当然也 比较实用,即通过微信“喵提醒”的方式来实现。在后面的大作业中,我们也会使用到。

代码语言:javascript
复制
### 对抗攻击监测
            detect_pred = model_detect_attack(advimg)
            # img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)
            print("detcet_pred:", detect_pred)
            if detect_pred > 0.5:
                id = 'tG00u9C'
                # 填写喵提醒中,发送的消息,这里放上前面提到的图片外链
                text = "出现对抗攻击风险!!"
                ts = str(time.time())  # 时间戳
                type = 'json'  # 返回内容格式
                request_url = "http://miaotixing.com/trigger?"
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47'}
                result = requests.post(request_url + "id=" + id + "&text=" + text + "&ts=" + ts + "&type=" + type,
                                    headers=headers)
            else:
                pred = imagenet_label2classname(predict_from_logits(model(advimg)))
                print("pred:", pred)

4.4整体实现部分

代码中分别进行了图片和视频读取操作,实现案例。当测试图片时,注释掉视频段代码;测试视频时,注释掉图片操作部分,注意修改路径。

代码语言:javascript
复制
import cvs
from cvs import *
import os
import time
import cv2
import copy
import torch
import requests
import aidlite_gpu
import torch.nn as nn
import torchvision.utils
import numpy as np
import sys
sys.path.append("..")
from yolov5_code.aidlux.utils import detect_postprocess, preprocess_img, draw_detect_res, extract_detect_res
# from utils import detect_postprocess, preprocess_img, draw_detect_res, extract_detect_res
from detect_adv_code import Model, Detect_Model
from torchvision.models import mobilenet_v2, resnet18
from advertorch.utils import predict_from_logits
from advertorch_examples.utils import ImageNetClassNameLookup
from advertorch.utils import NormalizeByChannelMeanStd
from advertorch_examples.utils import bhwc2bchw
from advertorch_examples.utils import bchw2bhwc
from advertorch.attacks import FGSM, LinfPGDAttack


device = "cuda" if torch.cuda.is_available() else "cpu"

normalize = NormalizeByChannelMeanStd(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
imagenet_label2classname = ImageNetClassNameLookup()

### 常规模型加载
model = mobilenet_v2(pretrained=True)
model.eval()
model = nn.Sequential(normalize, model)
model = model.to(device)

### 替身模型加载
model_su = resnet18(pretrained=True)
model_su.eval()
model_su = nn.Sequential(normalize, model_su)
model_su = model_su.to(device)

Attack_flag = True  #判断是否进行攻击
model_detect = Model().eval().to(device)
model_detect_attack = Detect_Model().eval().to(device)

###对抗攻击部分
def PGD_Attack(model, model_su, img_input):
    ### 数据预处理
    np_img = img_input[:,:,::-1] / 255.0
    img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)
    imagenet_label2classname = ImageNetClassNameLookup()
    ### 测试模型输出结果
    pred = imagenet_label2classname(predict_from_logits(model(img)))
    print("test output:", pred)
    ### 输出原label
    pred_label = predict_from_logits(model_su(img))
    ### 对抗攻击:PGD攻击算法
    adversary = LinfPGDAttack(
        model_su, eps=8/255, eps_iter=2/255, nb_iter=80,
        rand_init=True, targeted=False)
    ### 完成攻击,输出对抗样本
    advimg = adversary.perturb(img, pred_label)     ##torch.Size([1, 3, 24, 42])
    return advimg

###推理截取图片部分
# AidLite初始化:调用AidLite进行AI模型的加载与推理,需导入aidlite
aidlite = aidlite_gpu.aidlite()
# Aidlite模型路径
model_path = '/home/Lesson5_code_2/yolov5_code/aidlux/yolov5_car_best-fp16.tflite'
# 定义输入输出shape
in_shape = [1 * 640 * 640 * 3 * 4]
out_shape = [1 * 25200 * 6 * 4]
# 加载Aidlite检测模型:支持tflite, tnn, mnn, ms, nb格式的模型加载
aidlite.ANNModel(model_path, in_shape, out_shape, 4, 0)

'''图片操作部分'''
# # 读取图片进行推理
# # 设置测试集路径
# source = "/home/Lesson5_code_2/adv_code/test_images"
# images_list = os.listdir(source)
# print("images_list:", images_list)
# frame_id = 0
# # 读取数据集
# for image_name in images_list[:1]:
#     frame_id += 1
#     print("frame_id:", frame_id)
#     image_path = os.path.join(source, image_name)
#     frame = cvs.imread(image_path)  #(380, 676, 3)
#     # 预处理
#     img = preprocess_img(frame, target_shape=(640, 640), div_num=255, means=None, stds=None)
#     # 数据转换:因为setTensor_Fp32()需要的是float32类型的数据,所以送入的input的数据需为float32,大多数的开发者都会忘记将图像的数据类型转换为float32
#     aidlite.setInput_Float32(img, 640, 640)
#     # 模型推理API
#     aidlite.invoke()
#     # 读取返回的结果
#     pred = aidlite.getOutput_Float32(0)
#     # 数据维度转换
#     pred = pred.reshape(1, 25200, 6)[0]
#     # 模型推理后处理
#     pred = detect_postprocess(pred, frame.shape, [640, 640, 3], conf_thres=0.25, iou_thres=0.45)
#     # print("pred:", pred)
#     all_boxes = pred[0]
#     frame = frame.astype(np.uint8)
#     if len(all_boxes) > 0:
#         for box in all_boxes:
#             x, y, w, h = [int(t) for t in box[:4]]
#             cut_img = frame[y:(y+h), x:(x + w)]     #(44,118,3)
#             if Attack_flag:
#                 advimg = PGD_Attack(model, model_su, cut_img)   #torch.Size([1, 3, 44, 118]
#                 # print("advimg:", type(advimg), advimg.shape)
#             else:
#                 cut_img = copy.deepcopy(cut_img[:,:,::-1] / 255)
#                 advimg = torch.tensor(bhwc2bchw(cut_img))[None, :, :, :].float().to(device)
#             ### 无对抗攻击监测模型
#             # detect_pred = model_detect(advimg)
            ### 对抗攻击监测
            # detect_pred = model_detect_attack(advimg)
            # # img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)
            # print("detcet_pred:", detect_pred)
            # if detect_pred > 0.5:
            #     id = 'tG00u9C'
            #     # 填写喵提醒中,发送的消息,这里放上前面提到的图片外链
            #     text = "出现对抗攻击风险!!"
            #     ts = str(time.time())  # 时间戳
            #     type = 'json'  # 返回内容格式
            #     request_url = "http://miaotixing.com/trigger?"
            #     headers = {
            #         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47'}
            #     result = requests.post(request_url + "id=" + id + "&text=" + text + "&ts=" + ts + "&type=" + type,
            #                         headers=headers)
            # else:
            #     pred = imagenet_label2classname(predict_from_logits(model(advimg)))
            #     print("pred:", pred)


'''读取视频流部分'''
cap = cvs.VideoCapture("/home/Lesson5_code_2/AI_Vedio/test.avi")
frame_id = 0
while True:
    # 获取图像
    frame = cap.read()
    if frame is None:
        continue
    frame_id += 1
    print("="*60)
    print(f"frame_id: {frame_id}")
    # print(frame.shape)
    np_img = preprocess_img(frame, div_num=255, means=None, stds=None)
    print(np_img.shape)
    np_img = np_img[0, ...]
    img = torch.tensor(bhwc2bchw(np_img))[None, :, :, :].float().to(device)

    ###对抗攻击检测
    detect_pred =model_detect_attack(img)
    print(f"frame_id: {frame_id} 检测模型检测得分:{detect_pred.item():.4f}")
    cvs.imshow(frame)   #图片显示
    if detect_pred > 0.5:
        print("--->出现对抗风险图片!!!")
        id = 'tG00u9C'
        # 填写喵提醒中,发送的消息,这里放上前面提到的图片外链
        text = "出现对抗攻击风险!!"
        ts = str(time.time())  # 时间戳
        type = 'json'  # 返回内容格式
        request_url = "http://miaotixing.com/trigger?"

        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47'}

        result = requests.post(request_url + "id=" + id + "&text=" + text + "&ts=" + ts + "&type=" + type,
                               headers=headers)
    else:
        print("--->图片正常")
        pred = imagenet_label2classname(predict_from_logits(model(img)))
        print(pred)

4.5测试结果展示

1、图片测试操作展示。测试图片+喵提醒警告。

2、视频操作展示。视频流展示结果如下所示。输出终端显示风险图片与正常图片提示。告警端出现了一系列的告警提示。

视频

视频内容

5、总结

经过本次训练营实战的学习,了解智慧交通AI安全方面的重要性,模型易受攻击场景与对抗攻击方式,以及相应的防御策略,实现了智慧交通车辆检测安防整体流程过程学习与操作,成功应用于Aidlux移动端,经过两个多星期的学习,让我受益匪浅,对智慧交通AI攻防安全问题产生了浓厚的兴趣。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、背景介绍
  • 2、Aldlux使用操作流程
  • 3、AI对抗攻击与防御算法简介
    • 3.1、AI对抗攻击算法讲解
      • 3.2、AI安全防御算法讲解
      • 4、总体流程(车辆检测/检测框提取+对抗攻击+安全检测告警)
        • 4.1检测车辆特征提取
          • 4.2对抗样本生成
            • 4.3攻击检测与安全警告
              • 4.4整体实现部分
                • 4.5测试结果展示
                • 5、总结
                相关产品与服务
                人脸识别
                腾讯云神图·人脸识别(Face Recognition)基于腾讯优图强大的面部分析技术,提供包括人脸检测与分析、比对、搜索、验证、五官定位、活体检测等多种功能,为开发者和企业提供高性能高可用的人脸识别服务。 可应用于在线娱乐、在线身份认证等多种应用场景,充分满足各行业客户的人脸属性识别及用户身份确认等需求。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档