GIS之深度学习10:运行Faster RCNN算法

(未完成,待补充)


获取Faster RCNN源码

(开源的很多,论文里也有,在这里不多赘述)

替换自己的数据集(图片+标签文件)

(需要使用labeling生成标签文件)

打开终端,进入gpupytorch环境

运行voc_annotation.py文件生成与训练文件

E:\DeepLearningModel\Model01>activate gpupytorch(gpupytorch) E:\DeepLearningModel\Model01>python voc_annotation.py
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas.PYQHXLVVQ7VESDPUVUADXEVJOBGHJPAY.gfortran-win_amd64.dll
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas64__v0.3.21-gcc_10_3_0.dllwarnings.warn("loaded more than 1 DLL from .libs:\n%s" %
Generate txt in ImageSets.
train and val size 777
train size 699
Generate txt in ImageSets done.
Generate 2007_train.txt and 2007_val.txt for train.

 结果所示:

(gpupytorch) E:\DeepLearningModel\Model01>python voc_annotation.py
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas.PYQHXLVVQ7VESDPUVUADXEVJOBGHJPAY.gfortran-win_amd64.dll
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas64__v0.3.21-gcc_10_3_0.dllwarnings.warn("loaded more than 1 DLL from .libs:\n%s" %
Generate txt in ImageSets.
train and val size 777
train size 699
Generate txt in ImageSets done.
Generate 2007_train.txt and 2007_val.txt for train.
Generate 2007_train.txt and 2007_val.txt for train done.
|  leopard | 174 |
|     boar | 491 |
| roe_deer | 352 |(gpupytorch) E:\DeepLearningModel\Model01>

运行:train.py文件

import colorsys
import os
import timeimport numpy as np
import torch
import torch.nn as nn
from PIL import Image, ImageDraw, ImageFontfrom nets.frcnn import FasterRCNN
from utils.utils import (cvtColor, get_classes, get_new_img_size, resize_image,preprocess_input, show_config)
from utils.utils_bbox import DecodeBoxclass FRCNN(object):_defaults = {"model_path"    : 'logs/loss_2024_03_05_22_26_24.pth',"classes_path"  : 'model_data/voc_classes.txt',"backbone"      : "resnet50","confidence"    : 0.5,"nms_iou"       : 0.3,'anchors_size'  : [8, 16, 32],"cuda"          : True,}@classmethoddef 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)for name, value in kwargs.items():setattr(self, name, value)self._defaults[name] = value self.class_names, self.num_classes  = get_classes(self.classes_path)self.std    = torch.Tensor([0.1, 0.1, 0.2, 0.2]).repeat(self.num_classes + 1)[None]if self.cuda:self.std    = self.std.cuda()self.bbox_util  = DecodeBox(self.std, self.num_classes)#---------------------------------------------------#hsv_tuples = [(x / self.num_classes, 1., 1.) for x in range(self.num_classes)]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))self.generate()show_config(**self._defaults)#---------------------------------------------------##   载入模型#---------------------------------------------------#def generate(self):self.net    = FasterRCNN(self.num_classes, "predict", anchor_scales = self.anchors_size, backbone = self.backbone)device      = torch.device('cuda' if torch.cuda.is_available() else 'cpu')self.net.load_state_dict(torch.load(self.model_path, map_location=device))self.net    = self.net.eval()print('{} model, anchors, and classes loaded.'.format(self.model_path))if self.cuda:self.net = nn.DataParallel(self.net)self.net = self.net.cuda()#---------------------------------------------------##   检测图片#---------------------------------------------------#def detect_image(self, image, crop = False, count = False):#---------------------------------------------------##   计算输入图片的高和宽#---------------------------------------------------#image_shape = np.array(np.shape(image)[0:2])#---------------------------------------------------##   计算resize后的图片的大小,resize后的图片短边为600#---------------------------------------------------#input_shape = get_new_img_size(image_shape[0], image_shape[1])#---------------------------------------------------------##   在这里将图像转换成RGB图像,防止灰度图在预测时报错。#   代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB#---------------------------------------------------------#image       = cvtColor(image)#---------------------------------------------------------##   给原图像进行resize,resize到短边为600的大小上#---------------------------------------------------------#image_data  = resize_image(image, [input_shape[1], input_shape[0]])#---------------------------------------------------------##   添加上batch_size维度#---------------------------------------------------------#image_data  = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)with torch.no_grad():images = torch.from_numpy(image_data)if self.cuda:images = images.cuda()#-------------------------------------------------------------##   roi_cls_locs  建议框的调整参数#   roi_scores    建议框的种类得分#   rois          建议框的坐标#-------------------------------------------------------------#roi_cls_locs, roi_scores, rois, _ = self.net(images)#-------------------------------------------------------------##   利用classifier的预测结果对建议框进行解码,获得预测框#-------------------------------------------------------------#results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence)#---------------------------------------------------------##   如果没有检测出物体,返回原图#---------------------------------------------------------#           if len(results[0]) <= 0:return imagetop_label   = np.array(results[0][:, 5], dtype = 'int32')top_conf    = results[0][:, 4]top_boxes   = results[0][:, :4]#---------------------------------------------------------##   设置字体与边框厚度#---------------------------------------------------------#font        = ImageFont.truetype(font='model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))thickness   = int(max((image.size[0] + image.size[1]) // np.mean(input_shape), 1))#---------------------------------------------------------##   计数#---------------------------------------------------------#if count:print("top_label:", top_label)classes_nums    = np.zeros([self.num_classes])for i in range(self.num_classes):num = np.sum(top_label == i)if num > 0:print(self.class_names[i], " : ", num)classes_nums[i] = numprint("classes_nums:", classes_nums)#---------------------------------------------------------##   是否进行目标的裁剪#---------------------------------------------------------#if crop:for i, c in list(enumerate(top_label)):top, left, bottom, right = top_boxes[i]top     = max(0, np.floor(top).astype('int32'))left    = max(0, np.floor(left).astype('int32'))bottom  = min(image.size[1], np.floor(bottom).astype('int32'))right   = min(image.size[0], np.floor(right).astype('int32'))dir_save_path = "img_crop"if not os.path.exists(dir_save_path):os.makedirs(dir_save_path)crop_image = image.crop([left, top, right, bottom])crop_image.save(os.path.join(dir_save_path, "crop_" + str(i) + ".png"), quality=95, subsampling=0)print("save crop_" + str(i) + ".png to " + dir_save_path)#---------------------------------------------------------##   图像绘制#---------------------------------------------------------#for i, c in list(enumerate(top_label)):predicted_class = self.class_names[int(c)]box             = top_boxes[i]score           = top_conf[i]top, left, bottom, right = boxtop     = max(0, np.floor(top).astype('int32'))left    = max(0, np.floor(left).astype('int32'))bottom  = min(image.size[1], np.floor(bottom).astype('int32'))right   = min(image.size[0], np.floor(right).astype('int32'))label = '{} {:.2f}'.format(predicted_class, score)draw = ImageDraw.Draw(image)label_size = draw.textsize(label, font)label = label.encode('utf-8')# print(label, top, left, bottom, right)if top - label_size[1] >= 0:text_origin = np.array([left, top - label_size[1]])else:text_origin = np.array([left, top + 1])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, str(label,'UTF-8'), fill=(0, 0, 0), font=font)del drawreturn imagedef get_FPS(self, image, test_interval):#---------------------------------------------------##   计算输入图片的高和宽#---------------------------------------------------#image_shape = np.array(np.shape(image)[0:2])input_shape = get_new_img_size(image_shape[0], image_shape[1])#---------------------------------------------------------##   在这里将图像转换成RGB图像,防止灰度图在预测时报错。#   代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB#---------------------------------------------------------#image       = cvtColor(image)#---------------------------------------------------------##   给原图像进行resize,resize到短边为600的大小上#---------------------------------------------------------#image_data  = resize_image(image, [input_shape[1], input_shape[0]])#---------------------------------------------------------##   添加上batch_size维度#---------------------------------------------------------#image_data  = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)with torch.no_grad():images = torch.from_numpy(image_data)if self.cuda:images = images.cuda()roi_cls_locs, roi_scores, rois, _ = self.net(images)#-------------------------------------------------------------##   利用classifier的预测结果对建议框进行解码,获得预测框#-------------------------------------------------------------#results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence)t1 = time.time()for _ in range(test_interval):with torch.no_grad():roi_cls_locs, roi_scores, rois, _ = self.net(images)#-------------------------------------------------------------##   利用classifier的预测结果对建议框进行解码,获得预测框#-------------------------------------------------------------#results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence)t2 = time.time()tact_time = (t2 - t1) / test_intervalreturn tact_time#---------------------------------------------------##   检测图片#---------------------------------------------------#def get_map_txt(self, image_id, image, class_names, map_out_path):f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"),"w")#---------------------------------------------------##   计算输入图片的高和宽#---------------------------------------------------#image_shape = np.array(np.shape(image)[0:2])input_shape = get_new_img_size(image_shape[0], image_shape[1])#---------------------------------------------------------##   在这里将图像转换成RGB图像,防止灰度图在预测时报错。#   代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB#---------------------------------------------------------#image       = cvtColor(image)#---------------------------------------------------------##   给原图像进行resize,resize到短边为600的大小上#---------------------------------------------------------#image_data  = resize_image(image, [input_shape[1], input_shape[0]])#---------------------------------------------------------##   添加上batch_size维度#---------------------------------------------------------#image_data  = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0)with torch.no_grad():images = torch.from_numpy(image_data)if self.cuda:images = images.cuda()roi_cls_locs, roi_scores, rois, _ = self.net(images)#-------------------------------------------------------------##   利用classifier的预测结果对建议框进行解码,获得预测框#-------------------------------------------------------------#results = self.bbox_util.forward(roi_cls_locs, roi_scores, rois, image_shape, input_shape, nms_iou = self.nms_iou, confidence = self.confidence)#--------------------------------------##   如果没有检测到物体,则返回原图#--------------------------------------#if len(results[0]) <= 0:return top_label   = np.array(results[0][:, 5], dtype = 'int32')top_conf    = results[0][:, 4]top_boxes   = results[0][:, :4]for i, c in list(enumerate(top_label)):predicted_class = self.class_names[int(c)]box             = top_boxes[i]score           = str(top_conf[i])top, left, bottom, right = boxif predicted_class not in class_names:continuef.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom))))f.close()return 

 终端/编码器运行:

E:\DeepLearningModel\Model01>activate gpupytorch(gpupytorch) E:\DeepLearningModel\Model01>python train.py
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas.PYQHXLVVQ7VESDPUVUADXEVJOBGHJPAY.gfortran-win_amd64.dll
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas64__v0.3.21-gcc_10_3_0.dllwarnings.warn("loaded more than 1 DLL from .libs:\n%s" %
Number of devices: 1
initialize network with normal type
Load weights model_data/voc_weights_resnet.pth.Successful Load Key: ['extractor.0.weight', 'extractor.1.weight', 'extractor.1.bias', 'extractor.1.running_mean', 'extractor.1.running_var', 'extractor.1.num_batches_tracked', 'extractor.4.0.conv1.weight', 'extractor.4.0.bn1.weight', 'extractor.4.0.bn1.bias', 'extractor.4.0.bn1.running_mean', 'extractor.4.0.bn1.running_var', 'extractor.4.0.bn1.num_batches_tracked', 'extractor.4.0.conv2.weight', 'extractor.4.0.bn2.weight', 'extractor.4.0.bn2.bias', 'extractor.4.0.bn2.running_mean', 'extractor.4.0.bn2.running_var', 'e ……
Successful Load Key Num: 324Fail To Load Key: ['head.cls_loc.weight', 'head.cls_loc.bias', 'head.score.weight', 'head.score.bias'] ……
Fail To Load Key num: 4温馨提示,head部分没有载入是正常现象,Backbone部分没有载入是错误的。
Configurations:
----------------------------------------------------------------------
|                     keys |                                   values|
----------------------------------------------------------------------
|             classes_path |               model_data/voc_classes.txt|
|               model_path |        model_data/voc_weights_resnet.pth|
|              input_shape |                               [600, 600]|
|               Init_Epoch |                                        0|
|             Freeze_Epoch |                                       50|
|           UnFreeze_Epoch |                                      100|
|        Freeze_batch_size |                                        4|
|      Unfreeze_batch_size |                                        2|
|             Freeze_Train |                                     True|
|                  Init_lr |                                   0.0001|
|                   Min_lr |                   1.0000000000000002e-06|
|           optimizer_type |                                     adam|
|                 momentum |                                      0.9|
|            lr_decay_type |                                      cos|
|              save_period |                                        5|
|                 save_dir |                                     logs|
|              num_workers |                                        4|
|                num_train |                                      699|
|                  num_val |                                       78|
----------------------------------------------------------------------
Start Train
Epoch 1/100:   0%|                                                               | 0/174 [00:00<?, ?it/s<class 'dict'>]D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\_distributor_init.py:30: UserWarning: loaded more than 1 DLL from .libs:
D:\Anaconda\envs\gpupytorch\lib\site-packages\numpy\.libs\libopenblas.PYQHXLVVQ7VESDPUVUADXEVJOBGHJPAY.gfortran-win_amd64.dll

查看结果:

Calculate Map.
96.35% = boar AP        ||      score_threhold=0.5 : F1=0.81 ; Recall=97.92% ; Precision=69.12%
94.74% = leopard AP     ||      score_threhold=0.5 : F1=0.90 ; Recall=94.74% ; Precision=85.71%
94.97% = roe_deer AP    ||      score_threhold=0.5 : F1=0.86 ; Recall=96.88% ; Precision=77.50%
mAP = 95.35%
Get map done.
Epoch:100/100
Total Loss: 0.505 || Val Loss: 0.621
Save best model to best_epoch_weights.pth

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/274439.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据结构-链表(一)

一、链表简介 链表&#xff08;Linked List&#xff09;是一种常见的数据结构&#xff0c;用于存储和组织数据。与数组不同&#xff0c;链表的元素&#xff08;节点&#xff09;在内存中不必连续存储&#xff0c;而是通过指针链接在一起。 链表由多个节点组成&#xff0c;每个…

Vue3.0 所采用的 Composition Api 与 Vue2.x 使用的 Options Api 有什么不同?

开始之前 Composition API 可以说是Vue3的最大特点&#xff0c;那么为什么要推出Composition Api&#xff0c;解决了什么问题&#xff1f; 通常使用Vue2开发的项目&#xff0c;普遍会存在以下问题&#xff1a; 代码的可读性随着组件变大而变差每一种代码复用的方式&#xff…

【Docker】golang使用DockerFile正确食用指南

【Docker】golang使用DockerFile正确食用指南 大家好 我是寸铁&#x1f44a; 总结了一篇golang使用DockerFile正确食用指南✨ 喜欢的小伙伴可以点点关注 &#x1f49d; 问题背景 今天寸铁想让编写好的go程序在docker上面跑&#xff0c;要想实现这样的效果&#xff0c;就需要用…

mysql数据库(下)

目录 约束 约束的概念和分类 1、约束的概念&#xff1a; 2、约束的分类 1、主键约束 2、默认约束 3、非空约束 4、唯一约束 5、外键约束 约束 约束的概念和分类 1、约束的概念&#xff1a; 约束时作用于表中列上的规则&#xff0c;用于限制加入表的数据约束的存在保证…

Singularity(五)| 容器挂载和环境

Singularity&#xff08;五&#xff09;| 容器挂载和环境 我们可以按照如下方式运行 Singularity 容器&#xff1a; singularity shell samtoolssingularity exec samtools samtools helpsingularity run samtoolssingularity exec instance://samtools 在我们逐个详解容器运行…

Vue3全家桶 - VueRouter - 【2】重定向路由

重定向路由 在路由规则数组中&#xff0c;可采用 redirect 来重定向到另一个地址&#xff1a; 通常是将 / 重定向到 某个页面&#xff1b; 示例展示&#xff1a; router/index.js&#xff1a;import { createRouter, createWebHashHistory, createWebHistory } from vue-route…

Python安装第三方库

前言&#xff1a;大部分时候我们都是使用pip install去安装一些第三方库&#xff0c;但是偶尔也会有部分库无法安装&#xff08;最典型的就是dlib这个库&#xff09;&#xff0c;需要采取别的方法解决&#xff0c;这里做笔记记录一下。 使用国内镜像源安装 因为pypi的服务器在…

最简k8s部署(AWS Load Balancer Controller使用)

问题 我需要在k8s集群里面部署springboot服务&#xff0c;通过k8s ingress访问集群内部的springboot服务&#xff0c;应该怎么做&#xff1f; 这里假设已经准备好k8s集群&#xff0c;而且也准备好springboot服务的运行镜像了。这里我们将精力放在k8s服务编排上面。 一图胜千言…

基于SpringBoot的“医院信管系统”的设计与实现(源码+数据库+文档+PPT)

基于SpringBoot的“医院信管系统”的设计与实现&#xff08;源码数据库文档PPT) 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SpringBoot 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 功能结构图 系统首页界面图 用户注册界面图 医生…

es 查询案例分析

场景描述&#xff1a; 有这样一种场景&#xff0c;比如我们想搜索 title&#xff1a;Brown fox body&#xff1a;Brown fox 文章索引中有两条数据&#xff0c;兔子和狐狸两条数据 PUT /blogs/_bulk {"index": {"_id": 1}} {"title": "…

【鸿蒙 HarmonyOS 4.0】常用组件:List/Grid/Tabs

一、背景 列表页面&#xff1a;List组件和Grid组件&#xff1b; 页签切换&#xff1a;Tabs组件&#xff1b; 二、列表页面 在我们常用的手机应用中&#xff0c;经常会见到一些数据列表&#xff0c;如设置页面、通讯录、商品列表等。下图中两个页面都包含列表&#xff0c;“…

JVM知识整体学习

前言&#xff1a;本篇没有任何建设性的想法&#xff0c;只是我很早之前在学JVM时记录的笔记&#xff0c;只是想从个人网站迁移过来。文章其实就是对《深入理解JVM虚拟机》的提炼&#xff0c;纯基础知识&#xff0c;网上一搜一大堆。 一、知识点脑图 本文只谈论HotSpots虚拟机。…

如何使用US Domain Center和WordPress搭建非营利组织网站的详细指南

在今天的数字化时代&#xff0c;拥有一个专业、易于管理和更新的网站对于非营利组织&#xff08;例如慈善机构、NGO等&#xff09;至关重要。WordPress是一个功能强大且易于使用的网站构建平台&#xff0c;而美国域名中心 US Domain Center&#xff1a;US Domain Center 则是一…

软考71-上午题-【面向对象技术2-UML】-UML中的图2

一、用例图 上午题&#xff0c;考的少&#xff1b;下午题&#xff0c;考的多。 1-1、用例图的定义 用例图展现了一组用例、参与者以及它们之间的关系。 用例图用于对系统的静态用例图进行建模。 可以用下列两种方式来使用用例图&#xff1a; 1、对系统的语境建模&#xff1b…

LED显示屏的刷新频率及灰度等级

LED显示屏随着其在室内各种场所的广泛应用&#xff0c;无论是在指挥中心、监控中心还是演播厅中&#xff0c;都得到了越来越多的关注。然而&#xff0c;就LED显示屏系统的整体表现而言&#xff0c;这些显示屏能否满足用户的需求&#xff1f;显示的影像是否符合人眼的观赏要求&a…

2007-2021年中国省级知识产权保护指数数据

2007-2021年中国省级知识产权保护指数数据 1、时间&#xff1a;2007-2021年 2、范围&#xff1a;31省市 3、指标&#xff1a;&#xff1a;年份、省份、IPP&#xff08;知识产权保护指数&#xff09; 4、来源&#xff1a;全国知识产权发展状况报告 5、指标解释&#xff1a;…

mysql中insert … select锁范围

1、执行 insert … select 的时候&#xff0c;对目标表也不是锁全表&#xff0c;而是只锁住需要访问的资源。 例如&#xff0c; CREATE TABLE t (id int(11) NOT NULL AUTO_INCREMENT,c int(11) DEFAULT NULL,d int(11) DEFAULT NULL,PRIMARY KEY (id),UNIQUE KEY c (c) ) EN…

【java数据结构】HashMap和HashSet

目录 一.认识哈希表&#xff1a; 1.1什么是哈希表&#xff1f; 1.2哈希表的表示&#xff1a; 1.3常见哈希函数&#xff1a; 二.认识HashMap和HashSet: 2.1关于Map.Entry的说明:,> 2.2Map常用方法说明&#xff1a; 2.3HashMap的使用案例&#xff1a; 2.4Set常见方法…

代理IP如何应对自动化测试和爬虫检测

目录 一、代理IP在自动化测试和爬虫中的作用 二、代理IP的优缺点分析 1.优点 2.缺点 三、应对自动化测试和爬虫检测的策略 1.选择合适的代理IP 2.设置合理的请求频率和间隔 3.模拟人类行为模式 4.结合其他技术手段 四、案例与代码示例 五、总结 在自动化测试和爬虫开…

LoadBalancer (本地负载均衡)

1.loadbalancer本地负载均衡客户端 VS Nginx服务端负载均衡区别 Nginx是服务器负载均衡&#xff0c;客户端所有请求都会交给nginx&#xff0c;然后由nginx实现转发请求&#xff0c;即负载均衡是由服务端实现的。 loadbalancer本地负载均衡&#xff0c;在调用微服务接口时候&a…