交通路标识别(毕业设计)

简介: 交通路标识别(毕业设计)

概述:


代码获取:可私信

在TensorFlow中实现单镜头多盒检测器(SSD),用干检测和分类交通标志。该实现能够在具有 Intel Corei7-6700K的GTX1080实现40-45fos

请注意,此项目仍在进行中。现在的主要问题是模型过度拟合,


我目前正在先进行VOC2012的预培训,然后进行交通标志检测的转移学习。目前只检测到停车标志和人行横道标志。检测图像示例如下。


依赖库与代码


Skip to content
Product
Solutions
Open Source
Pricing
Search
Sign in
Sign up
georgesung
/
ssd_tensorflow_traffic_sign_detection
Public
Code
Issues
32
Pull requests
Actions
Projects
Security
Insights
ssd_tensorflow_traffic_sign_detection/inference.py /
@georgesung
georgesung Removed unused function run_inference_old()
Latest commit 88f1781 on Feb 15, 2017
 History
 1 contributor
189 lines (155 sloc)  6.08 KB
'''
Run inference using trained model
'''
import tensorflow as tf
from settings import *
from model import SSDModel
from model import ModelHelper
from model import nms
import numpy as np
from sklearn.model_selection import train_test_split
import cv2
import math
import os
import time
import pickle
from PIL import Image
import matplotlib.pyplot as plt
from moviepy.editor import VideoFileClip
from optparse import OptionParser
import glob
def run_inference(image, model, sess, mode, sign_map):
  """
  Run inference on a given image
  Arguments:
    * image: Numpy array representing a single RGB image
    * model: Dict of tensor references returned by SSDModel()
    * sess: TensorFlow session reference
    * mode: String of either "image", "video", or "demo"
  Returns:
    * Numpy array representing annotated image
  """
  # Save original image in memory
  image = np.array(image)
  image_orig = np.copy(image)
  # Get relevant tensors
  x = model['x']
  is_training = model['is_training']
  preds_conf = model['preds_conf']
  preds_loc = model['preds_loc']
  probs = model['probs']
  # Convert image to PIL Image, resize it, convert to grayscale (if necessary), convert back to numpy array
  image = Image.fromarray(image)
  orig_w, orig_h = image.size
  if NUM_CHANNELS == 1:
    image = image.convert('L')  # 8-bit grayscale
  image = image.resize((IMG_W, IMG_H), Image.LANCZOS)  # high-quality downsampling filter
  image = np.asarray(image)
  images = np.array([image])  # create a "batch" of 1 image
  if NUM_CHANNELS == 1:
    images = np.expand_dims(images, axis=-1)  # need extra dimension of size 1 for grayscale
  # Perform object detection
  t0 = time.time()  # keep track of duration of object detection + NMS
  preds_conf_val, preds_loc_val, probs_val = sess.run([preds_conf, preds_loc, probs], feed_dict={x: images, is_training: False})
  if mode != 'video':
    print('Inference took %.1f ms (%.2f fps)' % ((time.time() - t0)*1000, 1/(time.time() - t0)))
  # Gather class predictions and confidence values
  y_pred_conf = preds_conf_val[0]  # batch size of 1, so just take [0]
  y_pred_conf = y_pred_conf.astype('float32')
  prob = probs_val[0]
  # Gather localization predictions
  y_pred_loc = preds_loc_val[0]
  # Perform NMS
  boxes = nms(y_pred_conf, y_pred_loc, prob)
  if mode != 'video':
    print('Inference + NMS took %.1f ms (%.2f fps)' % ((time.time() - t0)*1000, 1/(time.time() - t0)))
  # Rescale boxes' coordinates back to original image's dimensions
  # Recall boxes = [[x1, y1, x2, y2, cls, cls_prob], [...], ...]
  scale = np.array([orig_w/IMG_W, orig_h/IMG_H, orig_w/IMG_W, orig_h/IMG_H])
  if len(boxes) > 0:
    boxes[:, :4] = boxes[:, :4] * scale
  # Draw and annotate boxes over original image, and return annotated image
  image = image_orig
  for box in boxes:
    # Get box parameters
    box_coords = [int(round(x)) for x in box[:4]]
    cls = int(box[4])
    cls_prob = box[5]
    # Annotate image
    image = cv2.rectangle(image, tuple(box_coords[:2]), tuple(box_coords[2:]), (0,255,0))
    label_str = '%s %.2f' % (sign_map[cls], cls_prob)
    image = cv2.putText(image, label_str, (box_coords[0], box_coords[1]), 0, 0.5, (0,255,0), 1, cv2.LINE_AA)
  return image
def generate_output(input_files, mode):
  """
  Generate annotated images, videos, or sample images, based on mode
  """
  # First, load mapping from integer class ID to sign name string
  sign_map = {}
  with open('signnames.csv', 'r') as f:
    for line in f:
      line = line[:-1]  # strip newline at the end
      sign_id, sign_name = line.split(',')
      sign_map[int(sign_id)] = sign_name
  sign_map[0] = 'background'  # class ID 0 reserved for background class
  # Create output directory 'inference_out/' if needed
  if mode == 'image' or mode == 'video':
    if not os.path.isdir('./inference_out'):
      try:
        os.mkdir('./inference_out')
      except FileExistsError:
        print('Error: Cannot mkdir ./inference_out')
        return
  # Launch the graph
  with tf.Graph().as_default(), tf.Session() as sess:
    # "Instantiate" neural network, get relevant tensors
    model = SSDModel()
    # Load trained model
    saver = tf.train.Saver()
    print('Restoring previously trained model at %s' % MODEL_SAVE_PATH)
    saver.restore(sess, MODEL_SAVE_PATH)
    if mode == 'image':
      for image_file in input_files:
        print('Running inference on %s' % image_file)
        image_orig = np.asarray(Image.open(image_file))
        image = run_inference(image_orig, model, sess, mode, sign_map)
        head, tail = os.path.split(image_file)
        plt.imsave('./inference_out/%s' % tail, image)
      print('Output saved in inference_out/')
    elif mode == 'video':
      for video_file in input_files:
        print('Running inference on %s' % video_file)
        video = VideoFileClip(video_file)
        video = video.fl_image(lambda x: run_inference(x, model, sess, mode, sign_map))
        head, tail = os.path.split(video_file)
        video.write_videofile('./inference_out/%s' % tail, audio=False)
      print('Output saved in inference_out/')
    elif mode == 'demo':
      print('Demo mode: Running inference on images in sample_images/')
      image_files = os.listdir('sample_images/')
      for image_file in image_files:
        print('Running inference on sample_images/%s' % image_file)
        image_orig = np.asarray(Image.open('sample_images/' + image_file))
        image = run_inference(image_orig, model, sess, mode, sign_map)
        plt.imshow(image)
        plt.show()
    else:
      raise ValueError('Invalid mode: %s' % mode)
if __name__ == '__main__':
  # Configure command line options
  parser = OptionParser()
  parser.add_option('-i', '--input_dir', dest='input_dir',
    help='Directory of input videos/images (ignored for "demo" mode). Will run inference on all videos/images in that dir')
  parser.add_option('-m', '--mode', dest='mode', default='image',
    help='Operating mode, could be "image", "video", or "demo"; "demo" mode displays annotated images from sample_images/')
  # Get and parse command line options
  options, args = parser.parse_args()
  input_dir = options.input_dir
  mode = options.mode
  if mode != 'video' and mode != 'image' and mode != 'demo':
    assert ValueError('Invalid mode: %s' % mode)
  if mode != 'demo':
    input_files = glob.glob(input_dir + '/*.*')
  else:
    input_files = []
  generate_output(input_files, mode)

Python 3.5+

TensorFlow v0.12.0

Pickle

OpenCV Python

Matplotlib(可选)


运用


将此存储库克降到某处,让我们将其称为$ROOT

从头开始训练模型:

7b18298a5557004a5a856a1127f5db5e_4a305475f18a4718a0fb888b550f0ae2.png

2de4ee3fefa8ced3b7fa82af17a2e4d7_1a43b18e47ad45458e37652188fddd19.png


代码流程


※Download the LISA Traffic Sign Dataset, and store it in a directory $LISA_DATA
※cd $LISA_DATA
※Follow instructions in the LISA Traffic Sign Dataset to create 'mergedAnnotations.csv' such that only stop signs and pedestrian ※crossing signs are shown
※cp $ROOT/data_gathering/create_pickle.py $LISA_DATA
※python create_pickle.py
※cd $ROOT
※ln -s $LISA_DATA/resized_images_* .
※ln -s $LISA_DATA/data_raw_*.p .
※python data_prep.py
※This performs box matching between ground-truth boxes and default ※boxes, and packages the data into a format used later in the ※pipeline
※python train.py
※This trains the SSD model
※python inference.py -m demo


效果


如上所述,该SSD实现能够在具有Intel Core i7 6700K的GTX 1080上实现40-45 fps

推理时间是神经网络推理时间和非最大抑制(NMS)时间的总和。总的来说,神经网络推断时间明显小干NMS时间,神经网络推理时间通常在7-8ms之间,而NMS时间在15-16ms之间。这里实现的NMS算法尚未优化,仅在CPU上运行,因此可以在那里进一步努力提高性能。

26490fbce4c13ae18ee4a75892f17ddb_32cb445eab4340c3b49b3dd3c2662235.png

78007217c9ed3fa8988a0fbc5c509ef7_000cc8d737e04aa993f2ba2d57ae3144.png


数据集


整个LISA交通标志数据集由47个不同的交通标志类别组成。因为我们只关注这些类的子集,所以我们只使用LSA数据集的子集。此外,我们忽略了没有找到匹配的默认框的所有训练样本,从而进一步减小了数据集的大小。由于这个过程,我们最终只能处理很少的数据。

为了改进这一问题,我们可以执行图像数据增强,和/或在更大的数据集上预训练模型(例如 VOC2012、ILSVRC)

下载链接:】(https://cvrr.ucsd.edu/LISA/lisa-traffic-sign-dataset.html)


代码可私信

代码可私信

代码可私信


相关文章
|
2月前
|
弹性计算 负载均衡 安全
阿里云国际站服务代理商:SLB批量采购怎么做预算?按地域还是业务系统拆分
阿里云国际站SLB批量采购预算需兼顾地域(定价/部署)与业务系统(成本归属)双维度,避免重复计费;ALB/NLB/CLB计费模型不同,不可混用单价;应按实际资源清单(产品类型、网络类型、环境、周期)精细化报价与对账。
|
4月前
|
数据采集 人工智能 自然语言处理
# 企业Agent为什么不能只靠RAG?RAG、规则引擎和Workflow的职责边界与架构设计
企业Agent不能仅靠RAG,因其仅解决“知道什么”;真实业务还需Rule Engine(确定性判断)、Workflow(任务编排)、LLM(理解表达)、业务系统(执行落地)与治理机制(权限风控),共同构成可信赖的企业智能能力底座。(239字)
|
2月前
|
人工智能 自然语言处理 监控
从问数工具到运营搭档:慧博科技基于Qoder Cloud Agents打造“小慧Claw”
慧博科技推出AI运营助手“小慧Claw”,基于Qoder Cloud Agents(QCA)构建智能体操作系统,实现从Prompt到Harness的范式升级。它支持自然语言问数、智能报表、经营预警等核心场景,将重复性运营工作自动化,使运营人员聚焦决策。接入QCA后,任务响应从小时级降至分钟级,报表口径准确率提升至95%,人效提升5倍。
339 0
|
8月前
|
人工智能 数据可视化 API
零基础零门槛!OpenClaw 阿里云无影云电脑一键部署、iMessage对接与千问Qwen3.6-Plus配置教程
2026年,OpenClaw(原Clawdbot)作为轻量化、高扩展的AI智能体框架,凭借极简部署、多平台兼容与强大的工具调用能力,成为个人与团队搭建专属AI助理的首选方案。对于零基础用户,**阿里云无影云电脑**提供了官方认证的OpenClaw专属镜像,预装Node.js 22、Git、Homebrew等全部运行依赖,无需复杂环境配置,即可实现“分钟级部署、7×24小时稳定运行”。同时,通过官方imessage-connector插件可无缝对接苹果iMessage平台,搭配**阿里云千问Qwen3.6-Plus**大模型的高性能API,可实现长文本理解、复杂推理、代码生成、多轮对话等核心能力
796 6
|
11月前
|
人工智能 自然语言处理 运维
企业数据分析系统建设费用,2026年降本增效的三大趋势
2026年,数据分析系统成企业降本增效战略刚需。全球投资达3850亿美元,中国占比超620亿美元(+18.7%)。瓴羊Quick BI以AI原生架构、“智能小Q”自然语言分析、多源实时接入及SaaS/私有化/混合云灵活部署,助力企业实现低门槛、高ROI的数据智能转型。(239字)
企业数据分析系统建设费用,2026年降本增效的三大趋势
|
人工智能 安全 应用服务中间件
AI 时代,网关更能打了
随着互联网从 Web 2.0 迈进到 AI 时代,用户和互联网的交互方式,AI 时代下互联网的内容生产流程都发生了显著的转变,这对基础设施(Infra)提出了新的诉求,也带来了新的机遇。Infra 包含的内容非常丰富,本文仅从网关层面分享笔者的所见所感所悟。
1620 135
|
C语言
【C语言篇】分支语句详解(超详细)
在 switch 语句中 case 语句和 default 语句是没有顺序要求的,只要顺序是满⾜实际需求的就可以。 不过我们通常是把 default ⼦句放在最后处理的。
1083 2
|
存储 弹性计算 安全
ECS与VPS技术角力:从算力成本到免备案雷区,企业服务器选型合规指南
在数字化浪潮中,服务器选择至关重要。ECS(云服务器)和VPS(虚拟专用服务器)是热门选项。ECS基于云计算,提供高可用性和弹性伸缩,适合大型项目;VPS通过分割物理服务器实现资源独立,成本较低,适合小型应用。两者在网络、存储及计算性能上各有优劣,需根据需求选择。国内并不存在合法的免备案服务器,建议严格遵守法规,确保网站合法运营。
1088 3
|
缓存 Linux UED
Yum与Dnf软件包管理器使用指南
Yum是RedHat、CentOS等Linux发行版中广泛使用的软件包管理器,它为用户提供了便捷的软件包安装、更新、管理等功能。然而,随着技术的发展,Red Hat已经开始将其软件包管理逐渐转移到dnf上。Dnf是yum的增强版,不仅继承了yum的核心功能,还在性能、用户体验等方面进行了诸多优化。在使用上,dnf与yum非常相似,两者在命令层面基本相同,只是名字有所区别。本文将详细介绍yum和dnf的常用命令及其使用方法,帮助用户更好地管理和维护系统中的软件包。
1243 3
|
存储 SQL JSON
使用 DataX 实现数据同步(高效的同步工具)
DataX 是阿里云 DataWorks 数据集成 的开源版本,主要就是用于实现数据间的离线同步。 DataX 致力于实现包括关系型数据库(MySQL、Oracle 等)、HDFS、Hive、ODPS、HBase、FTP 等 各种异构数据源(即不同的数据库) 间稳定高效的数据同步功能。
12564 0
使用 DataX 实现数据同步(高效的同步工具)