python中darks_在Python 3中使用YOLOv2
YOLOv2是Joseph Redmon提出的针对YOLO算法不足的改进版本,作者使用了一系列的方法对原来的YOLO多目标检测框架进行了改进,在保持原有速度的优势之下,精度上得以提升,此外作者提出了一种目标分类与检测的联合训练方法,通过这种方法YOLO9000可以同时在COCO和ImageNet数据集中进行训练,训练后的模型可以实现多达9000种物体的实时检测。
作者为YOLO算法设计了独有的深度学习框架darknet,因此没有提供Python的接口。在实验中,我找到了两种在Python 3中使用YOLOv2网络的方法。
第一种:为darknet添加Python接口
该项目使用了原始的darknet网络,需要使用cmake重新编译源码,因此在Linux上使用更为方便一些。
首先从git上下载该项目
git clone https://github.com/SidHard/py-yolo2.git
执行cmake生成项目
cmake .. && make
最后执行yolo.py测试项目,相应的网络结构.cfg文件保存在cfg文件夹中,权值.weight文件放在根目录下,这些可以从darknet的官方网站上下载使用。
第二种:使用keras
该项目使用了keras与tensorflow-gpu,因此可以在任何使用该框架的环境下运行,我在自己的程序中使用的该种方法。
首先下载源文件并且配置环境,可以使用anaconda环境或者在全局安装。
git clone https://github.com/allanzelener/yad2k.git
cd yad2k
# [Option 1] To replicate the conda environment:
conda env create -f environment.yml
source activate yad2k
# [Option 2] Install everything globaly.
pip install numpy
pip install tensorflow-gpu # CPU-only: conda install -c conda-forge tensorflow
pip install keras # Possibly older release: conda install keras
快速开始
从Darknet官方下载model:official YOLO website.
wget http://pjreddie.com/media/files/yolo.weights
将 Darknet YOLO_v2 model转换为Keras model.
./yad2k.py cfg/yolo.cfg yolo.weights model_data/yolo.h5
测试图片位于 images/文件夹.
./test_yolo.py model_data/yolo.h5
最后执行test_yolo就可以执行网络,在images/out/文件夹里可以看到执行效果。
dog.jpg
eagle.jpg
giraffe.jpg
horses.jpg
为了方便模型用于测试视频与图片,我对demo做了修改,相比原来的测试代码,能够直接移植到项目中去,对象化的程序也更易于修改,代码如下
#! /usr/bin/env python
"""Run a YOLO_v2 style detection model on test images."""
import cv2
import os
import time
import numpy as np
from keras import backend as K
from keras.models import load_model
from yad2k.models.keras_yolo import yolo_eval, yolo_head
class YOLO(object):
def __init__(self):
self.model_path = 'model_data/yolo.h5'
self.anchors_path = 'model_data/yolo_anchors.txt'
self.classes_path = 'model_data/coco_classes.txt'
self.score = 0.3
self.iou = 0.5
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(',')]
anchors = np.array(anchors).reshape(-1, 2)
return anchors
def generate(self):
model_path = os.path.expanduser(self.model_path)
assert model_path.endswith('.h5'), 'Keras model must be a .h5 file.'
self.yolo_model = load_model(model_path)
# Verify model, anchors, and classes are compatible
num_classes = len(self.class_names)
num_anchors = len(self.anchors)
# TODO: Assumes dim ordering is channel last
model_output_channels = self.yolo_model.layers[-1].output_shape[-1]
assert model_output_channels == num_anchors * (num_classes + 5), \
'Mismatch between model and given anchor and class sizes'
print('{} model, anchors, and classes loaded.'.format(model_path))
# Check if model is fully convolutional, assuming channel last order.
self.model_image_size = self.yolo_model.layers[0].input_shape[1:3]
self.is_fixed_size = self.model_image_size != (None, None)
# Generate output tensor targets for filtered bounding boxes.
# TODO: Wrap these backend operations with Keras layers.
yolo_outputs = yolo_head(self.yolo_model.output, self.anchors, len(self.class_names))
self.input_image_shape = K.placeholder(shape=(2, ))
boxes, scores, classes = yolo_eval(yolo_outputs, self.input_image_shape, score_threshold=self.score, iou_threshold=self.iou)
return boxes, scores, classes
def detect_image(self, image):
start = time.time()
y, x, _ = image.shape
if self.is_fixed_size: # TODO: When resizing we can use minibatch input.
resized_image = cv2.resize(image, tuple(reversed(self.model_image_size)), interpolation=cv2.INTER_CUBIC)
image_data = np.array(resized_image, dtype='float32')
else:
image_data = np.array(image, dtype='float32')
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.shape[0], image.shape[1]],
K.learning_phase(): 0
})
print('Found {} boxes for {}'.format(len(out_boxes), 'img'))
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)
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(y, np.floor(bottom + 0.5).astype('int32'))
right = min(x, np.floor(right + 0.5).astype('int32'))
print(label, (left, top), (right, bottom))
cv2.rectangle(image, (left, top), (right, bottom), (255, 0, 0), 2)
cv2.putText(image, label, (left, int(top - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
end = time.time()
print(end - start)
return image
def close_session(self):
self.sess.close()
def detect_vedio(video, yolo):
camera = cv2.VideoCapture(video)
cv2.namedWindow("detection", cv2.WINDOW_NORMAL)
while True:
res, frame = camera.read()
if not res:
break
image = yolo.detect_image(frame)
cv2.imshow("detection", image)
if cv2.waitKey(110) & 0xff == 27:
break
yolo.close_session()
def detect_img(img, yolo):
image = cv2.imread(img)
r_image = yolo.detect_image(image)
cv2.namedWindow("detection")
while True:
cv2.imshow("detection", r_image)
if cv2.waitKey(110) & 0xff == 27:
break
yolo.close_session()
if __name__ == '__main__':
yolo = YOLO()
img = 'E:\Documents\Downloads\YAD2K-master\YAD2K-master\images\horses.jpg'
video = 'E:\Documents\Documents\python\Traffic\data\person.avi'
detect_img(img, yolo)
detect_vedio(video, yolo)
python中darks_在Python 3中使用YOLOv2相关推荐
- Python分析离散心率信号(中)
Python分析离散心率信号(中) 一些理论和背景 心率信号不仅包含有关心脏的信息,还包含有关呼吸,短期血压调节,体温调节和荷尔蒙血压调节(长期)的信息.也(尽管不总是始终如一)与精神努力相关联,这并 ...
- PyCharm中Directory与Python package的区别
对于Python而言,有一点是要认识明确的,python作为一个相对而言轻量级的,易用的脚本语言(当然其功能并不仅限于此,在此只是讨论该特点),随着程序的增长,可能想要把它分成几个文件,以便逻辑更加清 ...
- 使用Python,OpenCV从静态背景中提取移动前景
使用Python,OpenCV从静态背景中提取移动前景 1. 效果图 2. 原理 3. 源码 参考 这篇博客将介绍OpenCV中的背景减法方法--即从静态背景中提取移动前景.在许多基于视觉的应用中,背 ...
- python 字典排序 最大键_Python中的列表、元祖、字典、集合操作大全
来源:http://suo.im/5HPGNT 在Python中有4种内建的数据结构:列表.元组.字典.集合.今天我们将会学习如何使用它们,以及它们如何使编程变得简单. 一.列表list 是处理一组有 ...
- python创建列向量_关于Numpy中的行向量和列向量详解
关于Numpy中的行向量和列向量详解 行向量 方式1 import numpy as np b=np.array([1,2,3]).reshape((1,-1)) print(b,b.shape) 结 ...
- Python培训分享:Python新版本中的6个新特性
Python在几年做了一个全面的升级,此次Python升级中有6个新特性,本期小编为大家介绍的Python培训教程就是关于介绍Python新版本中的6个新特性的,来看看下面的详细介绍. Python培 ...
- Python培训常识:Python面试中常被问到的几种设计模式要知道
学习Python技术大家都是为了日后能够找到适合自己的工作岗位,那么除了要学习好Python技术外,对于面试环节的问题也要有所了解,本期小编为大家介绍的Python培训教程就算关于Python面试中常 ...
- python解压zip文件_Python中最快解压zip文件的方法
假设现在的上下文(LCTT 译注:context,计算机术语,此处意为业务情景)是这样的:一个 zip 文件被上传到一个Web 服务中,然后 Python 需要解压这个 zip 文件然后分析和处理其中 ...
- python如何最适合web开发中的人工智能?
无论是初创公司还是跨国公司,Python都为每个人提供了一个很好的好处列表.它是最受欢迎和功能强大的高级编程语言,在2018年获得了极大的普及. 它的日益普及使得它能够进入一些最流行和最复杂的过程,如 ...
最新文章
- 计算机视觉方向简介 | 手机产品条码检测方案
- 用tensorflow还原PSENet网络
- 安装完最小化 RHEL/CentOS 7 后需要做的 30 件事情(三)码农网
- Sentinel(七)之网关限流
- sqlite4java下载_使用sqlite4java的UnsatisfiedLinkError,没有sqlite4java-osx-amd64
- python类2继承-抽象-多态
- xmu1214: 购物
- 大数据时代的全能日志分析专家--Splunk安装与实践
- 全网首发:神奇的WORD文字渲染效果,18个字符一组,每个字符渲染效果不同
- 《工业设计史》第八章:20世纪20、30年代的流行风格
- 去除wmv等视频认证的方法
- 南方cass简码识别大全_南方CASS简码成图的方法
- 「经济读物」第一本经济书 罗伯特.墨菲
- Excel —— 录制宏
- 基于STM32F1系列和LDV5语音模块的语音控制LCD屏幕的点亮
- C++指针与const的结合用法
- xxljob实战总结
- java播放mp3格式音频文件
- python整段代码注释-Python中注释(多行注释和单行注释)的用法实例
- 利用C语言获取设备的MAC address
热门文章
- 供应商与客户 连接平台 的谋合
- 浅谈MySQL存储引擎选择 InnoDB还是MyISAM
- 非常易于理解‘类'与'对象’ 间 属性 引用关系,暨《Python 中的引用和类属性的初步理解》读后感...
- mongoDB的配置以及运行
- 算法复习周------“贪心问题之‘单源最短路径’”
- SpringMVC框架使用注解执行定时任务(转)
- Asp.Net MVC学习总结(三)——过滤器你怎么看?
- JSON如何序列图片
- 实战PHP数据结构基础之队列
- 命令查询每个文件文件数