GithubHelp home page GithubHelp logo

bubbliiiing / faster-rcnn-pytorch Goto Github PK

View Code? Open in Web Editor NEW
1.5K 7.0 348.0 5.46 MB

这是一个faster-rcnn的pytorch实现的库,可以利用voc数据集格式的数据进行训练。

License: MIT License

Python 100.00%

faster-rcnn-pytorch's Introduction

Faster-Rcnn:Two-Stage目标检测模型在Pytorch当中的实现


目录

  1. 仓库更新 Top News
  2. 性能情况 Performance
  3. 所需环境 Environment
  4. 文件下载 Download
  5. 预测步骤 How2predict
  6. 训练步骤 How2train
  7. 评估步骤 How2eval
  8. 参考资料 Reference

Top News

2022-04:进行了大幅度的更新,支持step、cos学习率下降法、支持adam、sgd优化器选择、支持学习率根据batch_size自适应调整、新增图片裁剪。
BiliBili视频中的原仓库地址为:https://github.com/bubbliiiing/faster-rcnn-pytorch/tree/bilibili

2021-10:进行了大幅度的更新,增加了大量注释、增加了大量可调整参数、对代码的组成模块进行修改、增加fps、视频预测、批量预测等功能。

性能情况

训练数据集 权值文件名称 测试数据集 输入图片大小 mAP 0.5:0.95 mAP 0.5
VOC07+12 voc_weights_resnet.pth VOC-Test07 - - 80.36
VOC07+12 voc_weights_vgg.pth VOC-Test07 - - 77.46

所需环境

torch == 1.2.0

文件下载

训练所需的voc_weights_resnet.pth或者voc_weights_vgg.pth以及主干的网络权重可以在百度云下载。
voc_weights_resnet.pth是resnet为主干特征提取网络用到的;
voc_weights_vgg.pth是vgg为主干特征提取网络用到的;
链接: https://pan.baidu.com/s/1S6wG8sEXBeoSec95NZxmlQ
提取码: 8mgp

VOC数据集下载地址如下,里面已经包括了训练集、测试集、验证集(与测试集一样),无需再次划分:
链接: https://pan.baidu.com/s/1-1Ej6dayrx3g0iAA88uY5A
提取码: ph32

训练步骤

a、训练VOC07+12数据集

  1. 数据集的准备
    本文使用VOC格式进行训练,训练前需要下载好VOC07+12的数据集,解压后放在根目录

  2. 数据集的处理
    修改voc_annotation.py里面的annotation_mode=2,运行voc_annotation.py生成根目录下的2007_train.txt和2007_val.txt。

  3. 开始网络训练
    train.py的默认参数用于训练VOC数据集,直接运行train.py即可开始训练。

  4. 训练结果预测
    训练结果预测需要用到两个文件,分别是frcnn.py和predict.py。我们首先需要去frcnn.py里面修改model_path以及classes_path,这两个参数必须要修改。
    model_path指向训练好的权值文件,在logs文件夹里。
    classes_path指向检测类别所对应的txt。

    完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。

b、训练自己的数据集

  1. 数据集的准备
    本文使用VOC格式进行训练,训练前需要自己制作好数据集,
    训练前将标签文件放在VOCdevkit文件夹下的VOC2007文件夹下的Annotation中。
    训练前将图片文件放在VOCdevkit文件夹下的VOC2007文件夹下的JPEGImages中。

  2. 数据集的处理
    在完成数据集的摆放之后,我们需要利用voc_annotation.py获得训练用的2007_train.txt和2007_val.txt。
    修改voc_annotation.py里面的参数。第一次训练可以仅修改classes_path,classes_path用于指向检测类别所对应的txt。
    训练自己的数据集时,可以自己建立一个cls_classes.txt,里面写自己所需要区分的类别。
    model_data/cls_classes.txt文件内容为:

cat
dog
...

修改voc_annotation.py中的classes_path,使其对应cls_classes.txt,并运行voc_annotation.py。

  1. 开始网络训练
    训练的参数较多,均在train.py中,大家可以在下载库后仔细看注释,其中最重要的部分依然是train.py里的classes_path。
    classes_path用于指向检测类别所对应的txt,这个txt和voc_annotation.py里面的txt一样!训练自己的数据集必须要修改!
    修改完classes_path后就可以运行train.py开始训练了,在训练多个epoch后,权值会生成在logs文件夹中。

  2. 训练结果预测
    训练结果预测需要用到两个文件,分别是frcnn.py和predict.py。在frcnn.py里面修改model_path以及classes_path。
    model_path指向训练好的权值文件,在logs文件夹里。
    classes_path指向检测类别所对应的txt。

    完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。

预测步骤

a、使用预训练权重

  1. 下载完库后解压,在百度网盘下载frcnn_weights.pth,放入model_data,运行predict.py,输入
img/street.jpg
  1. 在predict.py里面进行设置可以进行fps测试和video视频检测。

b、使用自己训练的权重

  1. 按照训练步骤训练。
  2. 在frcnn.py文件里面,在如下部分修改model_path和classes_path使其对应训练好的文件;model_path对应logs文件夹下面的权值文件,classes_path是model_path对应分的类
_defaults = {
    #--------------------------------------------------------------------------#
    #   使用自己训练好的模型进行预测一定要修改model_path和classes_path!
    #   model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt
    #   如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改
    #--------------------------------------------------------------------------#
    "model_path"    : 'model_data/voc_weights_resnet.pth',
    "classes_path"  : 'model_data/voc_classes.txt',
    #---------------------------------------------------------------------#
    #   网络的主干特征提取网络,resnet50或者vgg
    #---------------------------------------------------------------------#
    "backbone"      : "resnet50",
    #---------------------------------------------------------------------#
    #   只有得分大于置信度的预测框会被保留下来
    #---------------------------------------------------------------------#
    "confidence"    : 0.5,
    #---------------------------------------------------------------------#
    #   非极大抑制所用到的nms_iou大小
    #---------------------------------------------------------------------#
    "nms_iou"       : 0.3,
    #---------------------------------------------------------------------#
    #   用于指定先验框的大小
    #---------------------------------------------------------------------#
    'anchors_size'  : [8, 16, 32],
    #-------------------------------#
    #   是否使用Cuda
    #   没有GPU可以设置成False
    #-------------------------------#
    "cuda"          : True,
}
  1. 运行predict.py,输入
img/street.jpg
  1. 在predict.py里面进行设置可以进行fps测试和video视频检测。

评估步骤

a、评估VOC07+12的测试集

  1. 本文使用VOC格式进行评估。VOC07+12已经划分好了测试集,无需利用voc_annotation.py生成ImageSets文件夹下的txt。
  2. 在frcnn.py里面修改model_path以及classes_path。model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。
  3. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。

b、评估自己的数据集

  1. 本文使用VOC格式进行评估。
  2. 如果在训练前已经运行过voc_annotation.py文件,代码会自动将数据集划分成训练集、验证集和测试集。如果想要修改测试集的比例,可以修改voc_annotation.py文件下的trainval_percent。trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1。train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1。
  3. 利用voc_annotation.py划分测试集后,前往get_map.py文件修改classes_path,classes_path用于指向检测类别所对应的txt,这个txt和训练时的txt一样。评估自己的数据集必须要修改。
  4. 在frcnn.py里面修改model_path以及classes_path。model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。
  5. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。

Reference

https://github.com/chenyuntc/simple-faster-rcnn-pytorch
https://github.com/eriklindernoren/PyTorch-YOLOv3
https://github.com/BobLiu20/YOLOv3_PyTorch

faster-rcnn-pytorch's People

Contributors

bubbliiiing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

faster-rcnn-pytorch's Issues

训练模型准确度

up主是否可以把每一轮训练的模型准确度也显示出来,仅仅显示loss有些不够,无法判断当前模型的好坏

可视化的问题

up主能不能把各种损失的曲线图可视化代码添进去,比如roi loss,total loss 等等

RuntimeError: Error(s) in loading state_dict for FasterRCNN:

训练出来的.pth无法加载,参数不匹配
详细报错:
Traceback (most recent call last):
File "/home/floatgray/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "", line 1, in
runfile('/home/floatgray/helmet_detection/faster-rcnn-pytorch-master/video.py', wdir='/home/floatgray/helmet_detection/faster-rcnn-pytorch-master')
File "/home/floatgray/文档/pycharm-professional-2019.3/pycharm-2019.3/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/home/floatgray/文档/pycharm-professional-2019.3/pycharm-2019.3/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/floatgray/helmet_detection/faster-rcnn-pytorch-master/video.py", line 9, in
frcnn = FRCNN()
File "/home/floatgray/helmet_detection/faster-rcnn-pytorch-master/frcnn.py", line 37, in init
self.generate()
File "/home/floatgray/helmet_detection/faster-rcnn-pytorch-master/frcnn.py", line 61, in generate
self.model.load_state_dict(torch.load(self.model_path))
File "/home/floatgray/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 839, in load_state_dict
self.class.name, "\n\t".join(error_msgs)))
RuntimeError: Error(s) in loading state_dict for FasterRCNN:
size mismatch for head.cls_loc.weight: copying a param with shape torch.Size([84, 2048]) from checkpoint, the shape in current model is torch.Size([12, 2048]).
size mismatch for head.cls_loc.bias: copying a param with shape torch.Size([84]) from checkpoint, the shape in current model is torch.Size([12]).
size mismatch for head.score.weight: copying a param with shape torch.Size([21, 2048]) from checkpoint, the shape in current model is torch.Size([3, 2048]).
size mismatch for head.score.bias: copying a param with shape torch.Size([21]) from checkpoint, the shape in current model is torch.Size([3]).

在训练是出现这种问题是?使用train.py出现这样的问题。

Epoch 1/50: 0%| | 0/4510 [00:00<?, ?it/s<class 'dict'>]
Traceback (most recent call last):
File "C:/Users/HP/Desktop/Fast_RCNNbilibili/faster-rcnn-pytorch/train.py", line 163, in
fit_ont_epoch(net,epoch,epoch_size,epoch_size_val,gen,gen_val,Freeze_Epoch,Cuda)
File "C:/Users/HP/Desktop/Fast_RCNNbilibili/faster-rcnn-pytorch/train.py", line 27, in fit_ont_epoch
for iteration, batch in enumerate(gen):
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\torch\utils\data\dataloader.py", line 819, in next
return self._process_data(data)
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\torch\utils\data\dataloader.py", line 846, in process_data
data.reraise()
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\torch_utils.py", line 369, in reraise
raise self.exc_type(msg)**

FileNotFoundError: Caught FileNotFoundError in DataLoader worker process 0.

Original Traceback (most recent call last):
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\torch\utils\data_utils\worker.py", line 178, in _worker_loop
data = fetcher.fetch(index)
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\torch\utils\data_utils\fetch.py", line 44, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\torch\utils\data_utils\fetch.py", line 44, in
data = [self.dataset[idx] for idx in possibly_batched_index]
File "C:\Users\HP\Desktop\Fast_RCNNbilibili\faster-rcnn-pytorch\utils\dataloader.py", line 100, in getitem
img,y=self.get_random_data(lines[index])
File "C:\Users\HP\Desktop\Fast_RCNNbilibili\faster-rcnn-pytorch\utils\dataloader.py", line 30, in get_random_data
image = Image.open(line[0])
File "E:\PYTHON\envs\Faster_RCNN\lib\site-packages\PIL\Image.py", line 2904, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\HP\Desktop\Fast'

作者您好,关于您更新后代码的batch_size问题

我有几个问题想问一下:
1.我看您除了对trainer.py和train.py进行修改,还对网络搭建文件的部分代码进行了修改,比如rpn.py和classifier.py,请问这是为什么,只是优化代码语句及逻辑还是由于修改了batch_size必须这样做,否则会影响正确性及效果。
2.batch_size>1是否还需要冻结BN层呢?

執行出現 Legacy autograd function with non-static forward method is deprecated.

您好,我在執行train.py的時候出現這個訊息
RuntimeError: Legacy autograd function with non-static forward method is deprecated. Please use new-style autograd function with static forward method.

檢查了一下 好像在trainer.py的
roi_cls_loc, roi_score = self.faster_rcnn.head(
features,
sample_roi,
sample_roi_index)
就停止了。
請問除了降torch版本以外,有其他方法嗎? 謝謝

关于resnet50改成resnet101的问题

大佬,我想在你写的resnet50基础上,改成resnet101

def resnet101():
    model = ResNet(Bottleneck, [3, 4, 23, 3])

我把resnet50中函数调用那里把6改成了23,就行了吧

关于坐标生成2007_train.txt中的问题

您好,我今天看了下生成的2007_train.txt文件中的label,我发现生成的注释少了几个,比如:

VOCdevkit/VOC2007/JPEGImages/000005.jpg 263,211,324,339,8 165,264,253,372,8 241,194,295,299,8

但是对应在000005.xml中,应该是5个:

<object>
		<name>chair</name>
		<pose>Rear</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>263</xmin>
			<ymin>211</ymin>
			<xmax>324</xmax>
			<ymax>339</ymax>
		</bndbox>
	</object>
	<object>
		<name>chair</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>165</xmin>
			<ymin>264</ymin>
			<xmax>253</xmax>
			<ymax>372</ymax>
		</bndbox>
	</object>
	<object>
		<name>chair</name>
		<pose>Unspecified</pose>
		<truncated>1</truncated>
		<difficult>1</difficult>
		<bndbox>
			<xmin>5</xmin>
			<ymin>244</ymin>
			<xmax>67</xmax>
			<ymax>374</ymax>
		</bndbox>
	</object>
	<object>
		<name>chair</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>241</xmin>
			<ymin>194</ymin>
			<xmax>295</xmax>
			<ymax>299</ymax>
		</bndbox>
	</object>
	<object>
		<name>chair</name>
		<pose>Unspecified</pose>
		<truncated>1</truncated>
		<difficult>1</difficult>
		<bndbox>
			<xmin>277</xmin>
			<ymin>186</ymin>
			<xmax>312</xmax>
			<ymax>220</ymax>
		</bndbox>
	</object>

我在voc_annotations.py中发现这行代码:

difficult = obj.find('difficult').text

请问为什么要过滤掉difficult标记的注释呢?这是官方建议的吗?

关于训练

训练的时候,开始冻结了预训练网络权重,后来又解冻了预训练网络权重,那么最终的预训练网络权重是不是也会变啊。

兄弟,你这代码有问题的

你的代码有问题的,你训练的数据竟然不是gt对anchor的偏移量,这让我很吃惊! 你是怎么做到的?

博主,test.py怎么没有了。之前用你的test.py跑出了这样的错误

python test.py
Traceback (most recent call last):
File "test.py", line 11, in
model.load_state_dict(torch.load("model_data/Epoch50-Total_Loss0.0958-Val_Loss0.1258.pth"))
File "/home/liu/anaconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 845, in load_state_dict
self.class.name, "\n\t".join(error_msgs)))
RuntimeError: Error(s) in loading state_dict for FasterRCNN:
size mismatch for head.cls_loc.weight: copying a param with shape torch.Size([28, 4096]) from checkpoint, the shape in current model is torch.Size([84, 4096]).
size mismatch for head.cls_loc.bias: copying a param with shape torch.Size([28]) from checkpoint, the shape in current model is torch.Size([84]).
size mismatch for head.score.weight: copying a param with shape torch.Size([7, 4096]) from checkpoint, the shape in current model is torch.Size([21, 4096]).
size mismatch for head.score.bias: copying a param with shape torch.Size([7]) from checkpoint, the shape in current model is torch.Size([21]).

map计算

用官方的voc2007进行测试的时候,map只有58.05%,而且预测的结果大多不太对。
我自己训练了一个单目标检测,最终测试map只有4%,这个问题是map计算的问题还是模型训练的问题呢?

关于faster rcnn的batch_size

请问为什么faster rcnn的batch_size在训练和验证的时候都只能设置为1?设置其他的值可以吗?

anchor.py中anchor生成问题

请教个问题

anchor = anchor_base.reshape((1, A, 4)) + \

前面通过generate_anchor_base()生成的anchor_base[0, :]的四个值对应的是h, w, h, w
_enumerate_shifted_anchor()中shift[0, :]的四个值对应的是w, h, w, h
那么anchor_base和shift相加生成的anchor[0, :]的四个值分别对应的是什么?
从后面的代码中看起是w, h, w, h

ROIPooling在哪里体现

up程序中途应该经过修改,之前看b站是用c写的roipooling那段,具体在哪个文件夹中体现的呢?原谅我太菜;)

如何对视频文件进行检测?

运行video.py文件时,我将capture=cv2.VideoCapture(0)中的0改成了MP4格式的文件路径,但是运行报错了,请问为什么呢?

主干网络Resnet50

源码里resnet50的model.layer4, model.avgpool执行的是分类classifier,他们没有参与特征提取工作,那主干网络提取特征的能力不是减弱了吗?

python predict.py

model_data/voc_weights_resnet.pth model, anchors, and classes loaded.
Input image filename:img/street.jpg
Traceback (most recent call last):
File "predict.py", line 11, in
img1 = input('Input image filename:')
File "", line 1, in
NameError: name 'img' is not defined

When I run the predict.py ,I faced this problem...

关于RPN模块的输出

RPN的输出rois, roi_indices的含义分别是什么呢?shape分别是多少?初学者比较模糊,希望作者讲一下,十分感谢。
我看到在后续的ROI池化及进一步分类的网络中输入只用到rois和roi_indices,而不是rpn_locs和 rpn_scores。

训练自己数据

我训练自己的数据,但在trainer.py里面44行左右有
bbox = bboxes[0]
label = labels[0]

这样不是每个图里面只能取第一个bbox来回归么。。。要是一个图里面有多个bbox后面的是不是都不会用到了

非极大值抑制

请问faster-rcnn有NMS的相关代码吗?为何我检测出来很多框重叠

内存溢出

楼主你知不知道运行解冻后的epoch会出现killed的现象该怎么解决?
image

博主好,关于Faster RCNN训练时报错cupy

报错问题:1. ImportError: CuPy is not correctly installed. 2.original error: DLL load failed: 找不到指定的模块。
3.File "cupy\cuda\device.pyx", line 9, in init cupy.cuda.device ImportError: DLL load failed: 找不到指定的模块。

关于这个报错我已经成功安装了cupy-cuda100,但还是训练不起来。

我的cuda版本是 CUDA 10.0.132 driver cuDNN版本是7.6.5 pytorch是windows cuda torch==1.2版本
GPU版本是NVIDIA GeForce GTX 950M

希望博主可以帮忙解决,非常感谢!Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.