热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

kerasyolo3master使用记录

keras-yolo3-master使用记录源码下载环境配置快速测试制作自己的项目生成yolo3所需的train.txt,val.txt,test.txt修改model_data下


keras-yolo3-master使用记录

    • 源码下载 环境配置 快速测试
    • 制作自己的项目
    • 生成yolo3所需的train.txt,val.txt,test.txt
    • 修改model_data下的文件,放入你的类别,coco,voc这两个文件都需要修改。
    • 训练自己的网络


你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。


源码下载 环境配置 快速测试

在macos windows liunx系统都测试过,本文采用macos


  1. 项目代码:https://github.com/qqwweee/keras-yolo3

  2. 下载yolo3weights :https://pjreddie.com/darknet/yolo/

    将yolo3weights文件夹放到keras-yolo3-master文件夹里

  3. terminal cd 到keras-yolo3-master文件夹
    生成现在权重下h5文件:
    python3 convert.py yolov3.cfg yolov3.weights model_data/yolo.h5

  4. 进行快速测试,看看能不能用。
    terminal cd到keras-yolo3-master目录下
    python3 yolo_video.py --image
    之后让你输入图片路径:(若将图片放在keras-yolo3-master文件夹下,直接输入相对地址即可)


制作自己的项目


  1. 下载VOC2007数据集
    下载地址: https://pjreddie.com/projects/pascal-voc-dataset-mirror/

  2. 这里面用到的文件夹是Annotation、ImageSets和JPEGImages

    其中文件夹Annotation中主要存放xml文件,每一个xml对应一张图像在这里插入图片描述;而ImageSets我们只需要用到Main文件夹,这里面存放的是一些文本文件,通常为train.txt、test.txt等,该文本文件里面的内容是需要用来训练或测试的图像的名字;JPEGImages文件夹中放我们已按统一规则命名好的原始图像。
    在这里插入图片描述

将自己数据转移到对应目录

// 将自己原始图片,标注过的图片放到VOC数据集相应位置,并生成训练集测试集验证集
//生成训练集测试集验证集对应txt文件,放入相应位置
#%%import os
import random
import shutil #拷贝文件并移动的库path = '/code/kaggle/wechat/' #自己的数据路径img = os.listdir(path + 'pyq') #所有原始图像img_xml = os.listdir(path + 'labeled') #所有xml文件
print('img_num: ',len(img))
print('img_xml_num: ',len(img_xml))#清空VOC数据集文件夹内容
path_img_ori = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/JPEGImages'
path_xml = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/Annotations'
img_ = os.listdir(path_img_ori)
xml_ = os.listdir(path_xml)
for img__ in img_:os.remove(os.path.join(path_img_ori,img__))
for xml__ in xml_:os.remove(os.path.join(path_xml,xml__))#生成VOC数据集文件夹内容
k = 0
for i in range(len(img)):path_img_ori = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/JPEGImages/'path_xml = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/Annotations/'#拷贝转移文件,并按0,1,2命名新文件#shutil.copyfile(old——path, new-path)shutil.copyfile(path + 'pyq/' + img[i] , path_img_ori + str(k) + '.' + 'jpg')shutil.copyfile(path + 'labeled/' + img_xml[i] , path_xml + str(k) + '.' + img_xml[i].split('.')[-1]) context.append(str(k))k = k+1trainval_percent = 0.2
train_percent = 0.8 #自己定比例
xmlfilepath = path_xml
txtsavepath = '/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/'
total_xml = os.listdir(xmlfilepath)num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)#到达的文件路径~/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt'ftrainval = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/trainval.txt', 'w')
ftest = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/test.txt', 'w')
ftrain = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/train.txt', 'w')
fval = open('/code/kaggle/keras-yolo3-master/VOCdevkit/VOC2007/ImageSets/Main/val.txt', 'w')for i in list:name = total_xml[i][:-4] + '\n'if i in trainval:ftrainval.write(name)if i in train:ftest.write(name)else:fval.write(name)else:ftrain.write(name)ftrainval.close()
ftrain.close()
fval.close()
ftest.close()#%%

生成yolo3所需的train.txt,val.txt,test.txt

打开keras-yolo3-master文件夹下voc_annatation.py文件进行修改

import xml.etree.ElementTree as ET
from os import getcwdsets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')] classes = ["dz_tx"] #这里改为自己标注数据集中的标签名def convert_annotation(year, image_id, list_file):in_file = open('/code/keras-yolo3-master/VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id),'rb')tree=ET.parse(in_file)root = tree.getroot()for obj in root.iter('object'):difficult = obj.find('difficult').textcls = obj.find('name').textif cls not in classes or int(difficult)==1:continuecls_id = classes.index(cls)xmlbox = obj.find('bndbox')b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))wd = getcwd()for year, image_set in sets:image_ids = open('/code/keras-yolo3-master/VOCdevkit/VOC%s/ImageSets/Main/%s.txt'%(year, image_set)).read().strip().split()list_file = open('%s.txt'%( image_set), 'w')for image_id in image_ids:list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg'%(wd, year, image_id))convert_annotation(year, image_id, list_file)list_file.write('\n')list_file.close()

修改model_data下的文件,放入你的类别,coco,voc这两个文件都需要修改。

一个标签占一行
在这里插入图片描述


训练自己的网络

直接复制替换原来train.py即可

此时自己在keras-yolo3-master下新建文件夹logs logs下再建文件夹000


  1. run时可能会报错
    AttributeError: module ‘keras.backend’ has no attribute ‘control_flow_ops’

    解决办法:https://blog.csdn.net/CAU_Ayao/article/details/89312354

  2. 可能Tensorboard报错
    我发现Tensorboard这行代码是灰色的,所以我把它作为释义不用了

  3. 建议先将epoch调小一些进行测试

"""
Retrain the YOLO model for your own dataset.
"""
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStoppingfrom yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_datadef _main():annotation_path = 'train.txt'log_dir = 'logs/000/'classes_path = 'model_data/voc_classes.txt'anchors_path = 'model_data/yolo_anchors.txt'class_names = get_classes(classes_path)anchors = get_anchors(anchors_path)input_shape = (416,416) # multiple of 32, hwmodel = create_model(input_shape, anchors, len(class_names) )train(model, annotation_path, input_shape, anchors, len(class_names), log_dir=log_dir)def train(model, annotation_path, input_shape, anchors, num_classes, log_dir='logs/'):model.compile(optimizer='adam', loss={'yolo_loss': lambda y_true, y_pred: y_pred})#################这个位置########################logging = TensorBoard(log_dir=log_dir)checkpoint = ModelCheckpoint(log_dir + "ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5",monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)batch_size = 10val_split = 0.1with open(annotation_path) as f:lines = f.readlines()np.random.shuffle(lines)num_val = int(len(lines)*val_split)num_train = len(lines) - num_valprint('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))model.fit_generator(data_generator_wrap(lines[:num_train], batch_size, input_shape, anchors, num_classes),steps_per_epoch=max(1, num_train//batch_size),validation_data=data_generator_wrap(lines[num_train:], batch_size, input_shape, anchors, num_classes),validation_steps=max(1, num_val//batch_size),epochs=500,initial_epoch=0)model.save_weights(log_dir + 'trained_weights.h5')def get_classes(classes_path):with open(classes_path) as f:class_names = f.readlines()class_names = [c.strip() for c in class_names]return class_namesdef get_anchors(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 create_model(input_shape, anchors, num_classes, load_pretrained=False, freeze_body=False,weights_path='model_data/yolo_weights.h5'):K.clear_session() # get a new sessionimage_input = Input(shape=(None, None, 3))h, w = input_shapenum_anchors = len(anchors)y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \num_anchors//3, num_classes+5)) for l in range(3)]model_body = yolo_body(image_input, num_anchors//3, num_classes)print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))if load_pretrained:model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)print('Load weights {}.'.format(weights_path))if freeze_body:# Do not freeze 3 output layers.num = len(model_body.layers)-7for i in range(num): model_body.layers[i].trainable = Falseprint('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})([*model_body.output, *y_true])model = Model([model_body.input, *y_true], model_loss)return model
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):n &#61; len(annotation_lines)np.random.shuffle(annotation_lines)i &#61; 0while True:image_data &#61; []box_data &#61; []for b in range(batch_size):i %&#61; nimage, box &#61; get_random_data(annotation_lines[i], input_shape, random&#61;True)image_data.append(image)box_data.append(box)i &#43;&#61; 1image_data &#61; np.array(image_data)box_data &#61; np.array(box_data)y_true &#61; preprocess_true_boxes(box_data, input_shape, anchors, num_classes)yield [image_data, *y_true], np.zeros(batch_size)def data_generator_wrap(annotation_lines, batch_size, input_shape, anchors, num_classes):n &#61; len(annotation_lines)if n&#61;&#61;0 or batch_size<&#61;0: return Nonereturn data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)if __name__ &#61;&#61; &#39;__main__&#39;:_main()

推荐阅读
  • 关于如何快速定义自己的数据集,可以参考我的前一篇文章PyTorch中快速加载自定义数据(入门)_晨曦473的博客-CSDN博客刚开始学习P ... [详细]
  • 图像因存在错误而无法显示 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Webpack5内置处理图片资源的配置方法
    本文介绍了在Webpack5中处理图片资源的配置方法。在Webpack4中,我们需要使用file-loader和url-loader来处理图片资源,但是在Webpack5中,这两个Loader的功能已经被内置到Webpack中,我们只需要简单配置即可实现图片资源的处理。本文还介绍了一些常用的配置方法,如匹配不同类型的图片文件、设置输出路径等。通过本文的学习,读者可以快速掌握Webpack5处理图片资源的方法。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • 突破MIUI14限制,自定义胶囊图标、大图标样式,支持任意APP
    本文介绍了如何突破MIUI14的限制,实现自定义胶囊图标和大图标样式,并支持任意APP。需要一定的动手能力和主题设计师账号权限或者会主题pojie。详细步骤包括应用包名获取、素材制作和封包获取等。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • Activiti7流程定义开发笔记
    本文介绍了Activiti7流程定义的开发笔记,包括流程定义的概念、使用activiti-explorer和activiti-eclipse-designer进行建模的方式,以及生成流程图的方法。还介绍了流程定义部署的概念和步骤,包括将bpmn和png文件添加部署到activiti数据库中的方法,以及使用ZIP包进行部署的方式。同时还提到了activiti.cfg.xml文件的作用。 ... [详细]
  • 颜色迁移(reinhard VS welsh)
    不要谈什么天分,运气,你需要的是一个截稿日,以及一个不交稿就能打爆你狗头的人,然后你就会被自己的才华吓到。------ ... [详细]
author-avatar
风让我离开
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有