DL之Yolov3:基于深度学习Yolov3算法实现视频目标检测之对《我要打篮球》视频段进行实时目标检测(一)

简介: DL之Yolov3:基于深度学习Yolov3算法实现视频目标检测之对《我要打篮球》视频段进行实时目标检测

输出结果

image.png






设计思路


DL之YoloV3:Yolo V3算法的简介(论文介绍)、架构详解、案例应用等配图集合之详细攻略

https://yunyaniu.blog.csdn.net/article/details/80143203#Yolo%20V3算法的案例应用





核心代码


Yolov3代码实现的时候,是将输入的视频分为帧图像进行目标检测的!


1、yolo.py文件

# -*- coding: utf-8 -*-

"""

Class definition of YOLO_v3 style detection model on image and video

"""

import colorsys

import os

from timeit import default_timer as timer

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

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.45,

       "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_eval(self.yolo_model.output, self.anchors,

               len(self.class_names), self.input_image_shape,

               score_threshold=self.score, iou_threshold=self.iou)

       return boxes, scores, classes

   def detect_image(self, image):

       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

       for i, c in reversed(list(enumerate(out_classes))):

           predicted_class = self.class_names[c]

           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))

           if top - label_size[1] >= 0:

               text_origin = np.array([left, top - label_size[1]])

           else:

               text_origin = np.array([left, top + 1])

           # My kingdom for a good redistributable image drawing library.

           for i in range(thickness):

               draw.rectangle(

                   [left + i, top + i, right - i, bottom - i],

                   outline=self.colors[c])

           draw.rectangle(

               [tuple(text_origin), tuple(text_origin + label_size)],

               fill=self.colors[c])

           draw.text(text_origin, label, fill=(0, 0, 0), font=font)

           del draw

       end = timer()

       print(end - start)

       return image

   def close_session(self):

       self.sess.close()

def detect_video(yolo, video_path, output_path=""):

   import cv2

   vid = cv2.VideoCapture(video_path)

   if not vid.isOpened():

       raise IOError("Couldn't open webcam or video")

   video_FourCC    = int(vid.get(cv2.CAP_PROP_FOURCC))

   video_fps       = vid.get(cv2.CAP_PROP_FPS)

   video_size      = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),

                       int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))

   isOutput = True if output_path != "" else False

   if isOutput:

       print("!!! TYPE:", type(output_path), type(video_FourCC), type(video_fps), type(video_size))

       out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size)

   accum_time = 0

   curr_fps = 0

   fps = "FPS: ??"

   prev_time = timer()

   while True:

       return_value, frame = vid.read()

       image = Image.fromarray(frame)

       image = yolo.detect_image(image)

       result = np.asarray(image)

       curr_time = timer()

       exec_time = curr_time - prev_time

       prev_time = curr_time

       accum_time = accum_time + exec_time

       curr_fps = curr_fps + 1

       if accum_time > 1:

           accum_time = accum_time - 1

           fps = "FPS: " + str(curr_fps)

           curr_fps = 0

       cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX,

                   fontScale=0.50, color=(255, 0, 0), thickness=2)

       cv2.namedWindow("result", cv2.WINDOW_NORMAL)

       cv2.imshow("result", result)

       if isOutput:

           out.write(result)

       if cv2.waitKey(1) & 0xFF == ord('q'):

           break

   yolo.close_session()



相关实践学习
在云上部署ChatGLM2-6B大模型(GPU版)
ChatGLM2-6B是由智谱AI及清华KEG实验室于2023年6月发布的中英双语对话开源大模型。通过本实验,可以学习如何配置AIGC开发环境,如何部署ChatGLM2-6B大模型。
相关文章
|
机器学习/深度学习 人工智能 算法
猫狗宠物识别系统Python+TensorFlow+人工智能+深度学习+卷积网络算法
宠物识别系统使用Python和TensorFlow搭建卷积神经网络,基于37种常见猫狗数据集训练高精度模型,并保存为h5格式。通过Django框架搭建Web平台,用户上传宠物图片即可识别其名称,提供便捷的宠物识别服务。
1687 55
|
机器学习/深度学习 人工智能 算法
基于Python深度学习的眼疾识别系统实现~人工智能+卷积网络算法
眼疾识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了4种常见的眼疾图像数据集(白内障、糖尿病性视网膜病变、青光眼和正常眼睛) 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Django框架搭建了一个Web网页平台可视化操作界面,实现用户上传一张眼疾图片识别其名称。
848 5
基于Python深度学习的眼疾识别系统实现~人工智能+卷积网络算法
|
机器学习/深度学习 数据采集 算法
短视频到底如何推荐的?深度剖析视频算法推送原理详细且专业的解读-优雅草卓伊凡-【01】短视频算法推荐之数据收集
短视频到底如何推荐的?深度剖析视频算法推送原理详细且专业的解读-优雅草卓伊凡-【01】短视频算法推荐之数据收集
2145 12
短视频到底如何推荐的?深度剖析视频算法推送原理详细且专业的解读-优雅草卓伊凡-【01】短视频算法推荐之数据收集
|
人工智能 算法 语音技术
Video-T1:视频生成实时手术刀!清华腾讯「帧树算法」终结闪烁抖动
清华大学与腾讯联合推出的Video-T1技术,通过测试时扩展(TTS)和Tree-of-Frames方法,显著提升视频生成的连贯性与文本匹配度,为影视制作、游戏开发等领域带来突破性解决方案。
666 4
Video-T1:视频生成实时手术刀!清华腾讯「帧树算法」终结闪烁抖动
|
机器学习/深度学习 人工智能 算法
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
宠物识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了37种常见的猫狗宠物种类数据集【'阿比西尼亚猫(Abyssinian)', '孟加拉猫(Bengal)', '暹罗猫(Birman)', '孟买猫(Bombay)', '英国短毛猫(British Shorthair)', '埃及猫(Egyptian Mau)', '缅因猫(Maine Coon)', '波斯猫(Persian)', '布偶猫(Ragdoll)', '俄罗斯蓝猫(Russian Blue)', '暹罗猫(Siamese)', '斯芬克斯猫(Sphynx)', '美国斗牛犬
899 29
【宠物识别系统】Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+图像识别
|
机器学习/深度学习 存储 算法
基于MobileNet深度学习网络的活体人脸识别检测算法matlab仿真
本内容主要介绍一种基于MobileNet深度学习网络的活体人脸识别检测技术及MQAM调制类型识别方法。完整程序运行效果无水印,需使用Matlab2022a版本。核心代码包含详细中文注释与操作视频。理论概述中提到,传统人脸识别易受非活体攻击影响,而MobileNet通过轻量化的深度可分离卷积结构,在保证准确性的同时提升检测效率。活体人脸与非活体在纹理和光照上存在显著差异,MobileNet可有效提取人脸高级特征,为无线通信领域提供先进的调制类型识别方案。
|
机器学习/深度学习 人工智能 算法
Enhance-A-Video:上海 AI Lab 推出视频生成质量增强算法,显著提升 AI 视频生成的真实度和细节表现
Enhance-A-Video 是由上海人工智能实验室、新加坡国立大学和德克萨斯大学奥斯汀分校联合推出的视频生成质量增强算法,能够显著提升视频的对比度、清晰度和细节真实性。
976 8
Enhance-A-Video:上海 AI Lab 推出视频生成质量增强算法,显著提升 AI 视频生成的真实度和细节表现
|
机器学习/深度学习 算法 安全
基于深度学习的路面裂缝检测算法matlab仿真
本项目基于YOLOv2算法实现高效的路面裂缝检测,使用Matlab 2022a开发。完整程序运行效果无水印,核心代码配有详细中文注释及操作视频。通过深度学习技术,将目标检测转化为回归问题,直接预测裂缝位置和类别,大幅提升检测效率与准确性。适用于实时检测任务,确保道路安全维护。 简介涵盖了算法理论、数据集准备、网络训练及检测过程,采用Darknet-19卷积神经网络结构,结合随机梯度下降算法进行训练。
|
机器学习/深度学习 算法 信息无障碍
基于GoogleNet深度学习网络的手语识别算法matlab仿真
本项目展示了基于GoogleNet的深度学习手语识别算法,使用Matlab2022a实现。通过卷积神经网络(CNN)识别手语手势,如"How are you"、"I am fine"、"I love you"等。核心在于Inception模块,通过多尺度处理和1x1卷积减少计算量,提高效率。项目附带完整代码及操作视频。
|
机器学习/深度学习 算法 数据安全/隐私保护
基于深度学习网络的宝石类型识别算法matlab仿真
本项目利用GoogLeNet深度学习网络进行宝石类型识别,实验包括收集多类宝石图像数据集并按7:1:2比例划分。使用Matlab2022a实现算法,提供含中文注释的完整代码及操作视频。GoogLeNet通过其独特的Inception模块,结合数据增强、学习率调整和正则化等优化手段,有效提升了宝石识别的准确性和效率。

热门文章

最新文章