0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看威廉希尔官方网站 视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

基于YOLOv3的红绿灯检测识别(Python源码可直接运行)

丫丫119 来源:未知 作者:肖冰 2019-09-18 15:43 次阅读

在实习的期间为公司写的红绿灯检测,基于YOLOv3的训练好的权重,不需要自己重新训练,只需要调用yolov3.weights,可以做到视频或图片中红绿灯的检测识别。

自动检测识别效果

1.红灯检测

2.绿灯检测

python源码

"""
Class definition of YOLO_v3 style detection model on image and video
"""

import colorsys
import os
from timeit import default_timer as timer
import cv2
import numpy as np
from keras import backend as K
from keras.models import load_model
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw

from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body
from yolo3.utils import letterbox_image
import os
from keras.utils import multi_gpu_model
import collections


class YOLO(object):
  _defaults = {
    "model_path": ''model_data/yolo.h5'',
    "anchors_path": ''model_data/yolo_anchors.txt'',
    "classes_path": ''model_data/coco_classes.txt'',
    "score" : 0.3,
    "iou" : 0.35,
    "model_image_size" : (416, 416),
    "gpu_num" : 1,
  }

  @classmethod
  def get_defaults(cls, n):
    if n in cls._defaults:
      return cls._defaults[n]
    else:
      return "Unrecognized attribute name ''" + n + "''"

  def __init__(self, **kwargs):
    self.__dict__.update(self._defaults) # set up default values
    self.__dict__.update(kwargs) # and update with user overrides
    self.class_names = self._get_class()
    self.anchors = self._get_anchors()
    self.sess = K.get_session()
    self.boxes, self.scores, self.classes = self.generate()

  def _get_class(self):
    classes_path = os.path.expanduser(self.classes_path)
    with open(classes_path) as f:
      class_names = f.readlines()
    class_names = [c.strip() for c in class_names]
    return class_names

  def _get_anchors(self):
    anchors_path = os.path.expanduser(self.anchors_path)
    with open(anchors_path) as f:
      anchors = f.readline()
    anchors = [float(x) for x in anchors.split('','')]
    return np.array(anchors).reshape(-1, 2)

  def generate(self):
    model_path = os.path.expanduser(self.model_path)
    assert model_path.endswith(''.h5''), ''Keras model or weights must be a .h5 file.''

    # Load model, or construct model and load weights.
    num_anchors = len(self.anchors)
    num_classes = len(self.class_names)
    is_tiny_version = num_anchors==6 # default setting
    try:
      self.yolo_model = load_model(model_path, compile=False)
    except:
      self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) 
        if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)
      self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match
    else:
      assert self.yolo_model.layers[-1].output_shape[-1] == 
        num_anchors/len(self.yolo_model.output) * (num_classes + 5), 
        ''Mismatch between model and given anchor and class sizes''

    print(''{} model, anchors, and classes loaded.''.format(model_path))

    # Generate colors for drawing bounding boxes.
    hsv_tuples = [(x / len(self.class_names), 1., 1.)
           for x in range(len(self.class_names))]
    self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    self.colors = list(
      map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
        self.colors))
    np.random.seed(10101) # Fixed seed for consistent colors across runs.
    np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes.
    np.random.seed(None) # Reset seed to default.

    # Generate output tensor targets for filtered bounding boxes.
    self.input_image_shape = K.placeholder(shape=(2, ))
    if self.gpu_num>=2:
      self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)
    boxes, scores, classes = yolo_, self.input_image_shape,
        score_threshold=self.score, iou_threshold=self.iou)
    return boxes, scores, classes

  def getColorList(self):
    dict = collections.defaultdict(list)

    # 红色
    lower_red = np.array([156, 43, 46])
    upper_red = np.array([180, 255, 255])
    color_list = []
    color_list.append(lower_red)
    color_list.append(upper_red)
    dict[''red''] = color_list

    # 红色2
    lower_red = np.array([0, 43, 46])
    upper_red = np.array([10, 255, 255])
    color_list = []
    color_list.append(lower_red)
    color_list.append(upper_red)
    dict[''red2''] = color_list

    # 橙色
    lower_orange = np.array([11, 43, 46])
    upper_orange = np.array([25, 255, 255])
    color_list = []
    color_list.append(lower_orange)
    color_list.append(upper_orange)
    dict[''orange''] = color_list

    # 黄色
    lower_yellow = np.array([26, 43, 46])
    upper_yellow = np.array([34, 255, 255])
    color_list = []
    color_list.append(lower_yellow)
    color_list.append(upper_yellow)
    dict[''yellow''] = color_list

    # 绿色
    lower_green = np.array([35, 43, 46])
    upper_green = np.array([77, 255, 255])
    color_list = []
    color_list.append(lower_green)
    color_list.append(upper_green)
    dict[''green''] = color_list
    return dict

  def get_color(self,frame):
    print(''go in get_color'')
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    maxsum = -100
    color = None
    color_dict = self.getColorList()
    score = 0
    type = ''black''
    for d in color_dict:
      mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])
      # print(cv2.inRange(hsv, color_dict[d][0], color_dict[d][1]))
      #cv2.imwrite(''images/triffic/'' + f + d + ''.jpg'', mask)
      binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1]
      binary = cv2.dilate(binary, None, iterations=2)
      img, cnts, hiera = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
      sum = 0
      for c in cnts:
        sum += cv2.contourArea(c)

      if sum > maxsum:
        maxsum = sum
        color = d
      if sum > score:
        score = sum
        type = d
    return type



  def detect_image(self, image,path):
    print(''class'',self._get_class())

    start = timer()

    if self.model_image_size != (None, None):
      assert self.model_image_size[0]%32 == 0, ''Multiples of 32 required''
      assert self.model_image_size[1]%32 == 0, ''Multiples of 32 required''
      boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))
    else:
      new_image_size = (image.width - (image.width % 32),
               image.height - (image.height % 32))
      boxed_image = letterbox_image(image, new_image_size)
    image_data = np.array(boxed_image, dtype=''float32'')

    print(image_data.shape)
    image_data /= 255.
    image_data = np.expand_dims(image_data, 0) # Add batch dimension.


    out_boxes, out_scores, out_classes = self.sess.run(
      [self.boxes, self.scores, self.classes],
      feed_dict={
        self.yolo_model.input: image_data,
        self.input_image_shape: [image.size[1], image.size[0]],
        K.learning_phase(): 0
      })

    print(''Found {} boxes for {}''.format(len(out_boxes), ''img''))

    font = ImageFont.truetype(font=''font/FiraMono-Medium.otf'',
          size=np.floor(3e-2 * image.size[1] + 0.5).astype(''int32''))
    thickness = (image.size[0] + image.size[1]) // 300
    thickness = 5
    print(''thickness'',thickness)
    print(''out_classes'',out_classes)
    my_class = [''traffic light'']
    imgcv = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)

    for i, c in reversed(list(enumerate(out_classes))):
      predicted_class = self.class_names[c]
      print(''predicted_class'',predicted_class)
      if predicted_class not in my_class:
        continue
      box = out_boxes[i]
      score = out_scores[i]

      label = ''{} {:.2f}''.format(predicted_class, score)

      draw = ImageDraw.Draw(image)

      label_size = draw.textsize(label, font)

      top, left, bottom, right = box
      top = max(0, np.floor(top + 0.5).astype(''int32''))
      left = max(0, np.floor(left + 0.5).astype(''int32''))
      bottom = min(image.size[1], np.floor(bottom + 0.5).astype(''int32''))
      right = min(image.size[0], np.floor(right + 0.5).astype(''int32''))
      print(label, (left, top), (right, bottom))
      img2 = imgcv[top:bottom, left:right]
      color = self.get_color(img2)
      cv2.imwrite(''images/triffic/''+path+str(i) + ''.jpg'', img2)
      if color== ''red'' or color == ''red2'':
        cv2.rectangle(imgcv, (left, top), (right, bottom), color=(0, 0, 255),
               lineType=2, thickness=8)
        cv2.putText(imgcv, ''{0} {1:.2f}''.format(color, score),
              (left, top - 15),
              cv2.FONT_HERSHEY_SIMPLEX,
              1.2, (0, 0, 255), 4,
              cv2.LINE_AA)
      elif color == ''green'':
        cv2.rectangle(imgcv, (left, top), (right, bottom), color=(0, 255, 0),
               lineType=2, thickness=8)
        cv2.putText(imgcv, ''{0} {1:.2f}''.format(color, score),
              (left, top - 15),
              cv2.FONT_HERSHEY_SIMPLEX,
              1.2, (0, 255, 0), 4,
              cv2.LINE_AA)
      else:
        cv2.rectangle(imgcv, (left, top), (right, bottom), color=(255, 0, 0),
               lineType=2, thickness=8)
        cv2.putText(imgcv, ''{0} {1:.2f}''.format(color, score),
              (left, top - 15),
              cv2.FONT_HERSHEY_SIMPLEX,
              1.2, (255, 0, 0), 4,
              cv2.LINE_AA)

      print(imgcv.shape)
    end = timer()
    print(end - start)
    return imgcv

  def close_session(self):
    self.sess.close()

def detect_img(yolo, img_path,fname):
  img = Image.open(img_path)
  import time
  t1 = time.time()

  img = yolo.detect_image(img,fname)
  print(''time: {}''.format(time.time() - t1))
  return img
  #yolo.close_session()

if __name__ == ''__main__'':
  yolo = YOLO()
  video_full_path = ''images/triffic.mp4''
  output = ''images/res.avi''
  cap = cv2.VideoCapture(video_full_path)
  cap.set(cv2.CAP_PROP_POS_FRAMES, 1) # 设置要获取的帧号

  fourcc = cv2.VideoWriter_fourcc(*''XVID'')
  fps = cap.get(cv2.CAP_PROP_FPS)
  size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

  out = cv2.VideoWriter(output, fourcc, fps, size)
  ret = True
  count = 0
  while ret :
    count+=1
    ret, frame = cap.read()
    if not ret :
      print(''结束'')
      break
    image = Image.fromarray(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
    image = yolo.detect_image(image,''pic'')
    out.write(image)

  cap.release()
  out.release()
  cv2.destroyAllWindows()
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 检测识别
    +关注

    关注

    0

    文章

    9

    浏览量

    7237
  • python
    +关注

    关注

    56

    文章

    4795

    浏览量

    84660
收藏 人收藏

    评论

    相关推荐

    Labview 编程红绿灯

    刚开始学习Labview,写了个红绿灯的程试,因为不怎么会C,C++,所以直接用编,请高手指点下.
    发表于 08-11 09:41

    红绿灯小程序

    `初学,搞个红绿灯小程序。勿拍。。。`
    发表于 08-30 15:02

    交通红绿灯

    本帖最后由 samuergao 于 2014-7-3 14:13 编辑 交通灯,并显示当前时间和倒计时,包含了单条路遇到人行道的红绿灯,还有十字路口的红绿灯,大家帮看看有的改进没有。
    发表于 07-03 12:12

    红绿灯问题求助?

    求做个红绿灯 就一个路的红绿灯
    发表于 10-22 10:53

    【分享】红绿灯的设计

    本帖最后由 elecfans跑堂 于 2015-9-16 10:49 编辑 红绿灯 的设计,大神看看
    发表于 09-15 22:37

    红绿灯

    `功能:1实现倒计时2实现黄灯闪烁3实现人行道红绿灯提示 `
    发表于 12-28 14:55

    基于51单片机的红绿灯设计

    这是一个基于51单片机的红绿灯设计,可以实现红绿灯的功能,同时还有特殊情况是单向通行。
    发表于 01-06 14:30 66次下载

    005——带时间显示的红绿灯

    005——带时间显示的红绿灯.........................
    发表于 04-28 09:49 18次下载

    红绿灯源程序

    红绿灯源程序,感兴趣的小伙伴们可以看看。
    发表于 06-17 15:42 32次下载

    红绿灯的供电状况解析

    很多红绿灯则是“黑户”(并不代表违规哦),它们的电则是从附近“借”来的,来源也是五花八门:附近的路灯、企业、公变台区等等……这些红绿灯,供电公司一般是不知道它的运行情况的
    的头像 发表于 12-04 16:53 6729次阅读

    如何使用Arduino Nano控制红绿灯

    本文将介绍如何基于一个简单PCB洞洞板制作红绿灯,并通过Arduino Nano R3对它进行控制。
    的头像 发表于 04-08 15:19 5357次阅读
    如何使用Arduino Nano控制<b class='flag-5'>红绿灯</b>

    双路红绿灯开源分享

    电子发烧友网站提供《双路红绿灯开源分享.zip》资料免费下载
    发表于 10-31 11:14 1次下载
    双路<b class='flag-5'>红绿灯</b>开源分享

    红绿灯识别知识点

    红绿灯识别是自动驾驶中最为基础的功能,识别方法主要有两种,一种基于视觉图像识别,一种基于v2x。 v2x,即通过红绿灯自己实时发送信号状态
    发表于 06-06 09:54 0次下载
    <b class='flag-5'>红绿灯</b><b class='flag-5'>识别</b>知识点

    Arduino迷你红绿灯

    电子发烧友网站提供《Arduino迷你红绿灯.zip》资料免费下载
    发表于 06-30 14:30 0次下载
    Arduino迷你<b class='flag-5'>红绿灯</b>

    深入浅出Yolov3Yolov4

    Yolov3是目标检测Yolo系列非常非常经典的算法,不过很多同学拿到Yolov3或者Yolov4的cfg文件时,并不知道如何直观的可视化查看网络结构。
    的头像 发表于 01-11 10:42 787次阅读
    深入浅出<b class='flag-5'>Yolov3</b>和<b class='flag-5'>Yolov</b>4