《Keras 2 :使用 RetinaNet 进行对象检测》:此文为AI自动翻译

《Keras 2 :使用 RetinaNet 进行对象检测》

作者:Srihari Humbarwadi
创建日期:2020/05/17
最后修改日期:2023/07/10
描述:实施 RetinaNet:用于密集对象检测的焦点损失。

(i) 此示例使用 Keras 2

 在 Colab 中查看 •


介绍

目标检测是计算机中非常重要的问题 视觉。在这里,模型的任务是定位 图像,同时将它们分为不同的类别。 对象检测模型大致可分为“单阶段”和 “两级”探测器。两级检测器通常更准确,但在 变慢的代价。在此示例中,我们将实现 RetinaNet, 一种流行的单级检测器,准确且运行速度快。 RetinaNet 使用特征金字塔网络来有效地检测 多个尺度,并引入了一种新的损失,即 Focal loss 函数,以减轻 极端的前景-背景阶级不平衡问题。

引用:

  • RetinaNet 纸
  • 特征金字塔网络论文
import os
import re
import zipfileimport numpy as np
import tensorflow as tf
from tensorflow import kerasimport matplotlib.pyplot as plt
import tensorflow_datasets as tfds

下载 COCO2017 数据集

对包含大约 118k 张图像的整个 COCO2017 数据集进行训练需要一个 ),因此我们将使用 ~500 张图像的较小子集 trained 在此示例中。

url = "https://github.com/srihari-humbarwadi/datasets/releases/download/v0.1.0/data.zip"
filename = os.path.join(os.getcwd(), "data.zip")
keras.utils.get_file(filename, url)with zipfile.ZipFile("data.zip", "r") as z_fp:z_fp.extractall("./")
Downloading data from https://github.com/srihari-humbarwadi/datasets/releases/download/v0.1.0/data.zip 560529408/560525318 [==============================] - 7s 0us/step 560537600/560525318 [==============================] - 7s 0us/step 

实现实用程序函数

边界框可以用多种方式表示,最常见的格式是:

  • 存储角的坐标[xmin, ymin, xmax, ymax]
  • 存储中心和框尺寸的坐标[x, y, width, height]

由于我们需要这两种格式,因此我们将实现用于转换 在格式之间。

def swap_xy(boxes):"""Swaps order the of x and y coordinates of the boxes.    Arguments:
      boxes: A tensor with shape `(num_boxes, 4)` representing bounding boxes.    Returns:
      swapped boxes with shape same as that of boxes.
    """return tf.stack([boxes[:, 1], boxes[:, 0], boxes[:, 3], boxes[:, 2]], axis=-1)def convert_to_xywh(boxes):"""Changes the box format to center, width and height.    Arguments:
      boxes: A tensor of rank 2 or higher with a shape of `(..., num_boxes, 4)`
        representing bounding boxes where each box is of the format
        `[xmin, ymin, xmax, ymax]`.    Returns:
      converted boxes with shape same as that of boxes.
    """return tf.concat([(boxes[..., :2] + boxes[..., 2:]) / 2.0, boxes[..., 2:] - boxes[..., :2]],axis=-1,)def convert_to_corners(boxes):"""Changes the box format to corner coordinates    Arguments:
      boxes: A tensor of rank 2 or higher with a shape of `(..., num_boxes, 4)`
        representing bounding boxes where each box is of the format
        `[x, y, width, height]`.    Returns:
      converted boxes with shape same as that of boxes.
    """return tf.concat([boxes[..., :2] - boxes[..., 2:] / 2.0, boxes[..., :2] + boxes[..., 2:] / 2.0],axis=-1,)

计算成对交并集 (IOU)

正如我们将在示例后面看到的那样,我们将分配真值框 以根据重叠范围锚定框。这将要求我们 计算所有锚点之间的交并比 (IOU) 框和真实框对。

def compute_iou(boxes1, boxes2):"""Computes pairwise IOU matrix for given two sets of boxes    Arguments:
      boxes1: A tensor with shape `(N, 4)` representing bounding boxes
        where each box is of the format `[x, y, width, height]`.
        boxes2: A tensor with shape `(M, 4)` representing bounding boxes
        where each box is of the format `[x, y, width, height]`.    Returns:
      pairwise IOU matrix with shape `(N, M)`, where the value at ith row
        jth column holds the IOU between ith box and jth box from
        boxes1 and boxes2 respectively.
    """boxes1_corners = convert_to_corners(boxes1)boxes2_corners = convert_to_corners(boxes2)lu = tf.maximum(boxes1_corners[:, None, :2], boxes2_corners[:, :2])rd = tf.minimum(boxes1_corners[:, None, 2:], boxes2_corners[:, 2:])intersection = tf.maximum(0.0, rd - lu)intersection_area = intersection[:, :, 0] * intersection[:, :, 1]boxes1_area = boxes1[:, 2] * boxes1[:, 3]boxes2_area = boxes2[:, 2] * boxes2[:, 3]union_area = tf.maximum(boxes1_area[:, None] + boxes2_area - intersection_area, 1e-8)return tf.clip_by_value(intersection_area / union_area, 0.0, 1.0)def visualize_detections(image, boxes, classes, scores, figsize=(7, 7), linewidth=1, color=[0, 0, 1]
):"""Visualize Detections"""image = np.array(image, dtype=np.uint8)plt.figure(figsize=figsize)plt.axis("off")plt.imshow(image)ax = plt.gca()for box, _cls, score in zip(boxes, classes, scores):text = "{}: {:.2f}".format(_cls, score)x1, y1, x2, y2 = boxw, h = x2 - x1, y2 - y1patch = plt.Rectangle([x1, y1], w, h, fill=False, edgecolor=color, linewidth=linewidth)ax.add_patch(patch)ax.text(x1,y1,text,bbox={"facecolor": color, "alpha": 0.4},clip_box=ax.clipbox,clip_on=True,)plt.show()return ax

实现 Anchor 生成器

锚框是模型用于预测边界的固定大小的框 对象的框。它通过回归位置 对象的中心和锚框的中心,然后使用宽度 和锚点框的高度来预测对象的相对比例。在 在 RetinaNet 的情况下,给定特征图上的每个位置都有 9 个锚框 (三个比例和三个比率)。

class AnchorBox:"""Generates anchor boxes.    This class has operations to generate anchor boxes for feature maps at
    strides `[8, 16, 32, 64, 128]`. Where each anchor each box is of the
    format `[x, y, width, height]`.    Attributes:
      aspect_ratios: A list of float values representing the aspect ratios of
        the anchor boxes at each location on the feature map
      scales: A list of float values representing the scale of the anchor boxes
        at each location on the feature map.
      num_anchors: The number of anchor boxes at each location on feature map
      areas: A list of float values representing the areas of the anchor
        boxes for each feature map in the feature pyramid.
      strides: A list of float value representing the strides for each feature
        map in the feature pyramid.
    """def __init__(self):self.aspect_ratios = [0.5, 1.0, 2.0]self.scales = [2 ** x for x in [0, 1 / 3, 2 / 3]]self._num_anchors = len(self.aspect_ratios) * len(self.scales)self._strides = [2 ** i for i in range(3, 8)]self._areas = [x ** 2 for x in [32.0, 64.0, 128.0, 256.0, 512.0]]self._anchor_dims = self._compute_dims()def _compute_dims(self):"""Computes anchor box dimensions for all ratios and scales at all levels
        of the feature pyramid.
        """anchor_dims_all = []for area in self._areas:anchor_dims = []for ratio in self.aspect_ratios:anchor_height = tf.math.sqrt(area / ratio)anchor_width = area / anchor_heightdims = tf.reshape(tf.stack([anchor_width, anchor_height], axis=-1), [1, 1, 2])for scale in self.scales:anchor_dims.append(scale * dims)anchor_dims_all.append(tf.stack(anchor_dims, axis=-2))return anchor_dims_alldef _get_anchors(

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

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

相关文章

webmin配置终端显示样式,模仿UbuntuDesktop终端

webmin配置终端显示样式,模仿UbuntuDesktop终端 在webmin中,默认情况下是没有图形化桌面的,因此终端界面也不会像 Ubuntu Desktop 那样有预设的紫色背景和颜色主题。不过,你可以通过修改 ~/.bashrc 文件,并结合安装和…

PyTorch-基础(CUDA、Dataset、transforms、卷积神经网络、VGG16)

PyTorch-基础 环境准备 CUDA Toolkit安装(核显跳过此步骤) CUDA Toolkit是NVIDIA的开发工具,里面提供了各种工具、如编译器、调试器和库 首先通过NVIDIA控制面板查看本机显卡驱动对应的CUDA版本,如何去下载对应版本的Toolkit工…

AWS-SAA中文版题库

一家公司收集多大洲城市的温度、湿度和大气压数据。该公司每天从每个站点收集的平均数据量为500GB。每个站点都有高速互联网连接。该公司希望尽快将所有这些全球站点的数据聚合到一个AmazonS3存储桶中。解决方案必须将操作复杂性降至最低。哪种解决方案满足这些要求&#xff1f…

Git操作整体流程

文章目录 1.Git创建个人仓库2、Git全局配置3、Git本地管理4. Git本地管理常用命令汇总5、使用Git命令将项目提交到远程码云管理6.使用IDEA进行管理7、Idea里面的终端8、关于提交总结 1.Git创建个人仓库 打开https://gitee.com/,登录个人账号,右上角加号…

微相E316实现FM电台监听

前面介绍了基于Matlab、矢量信号器或微相E316、HackRF One实现AM和FM调制解调,今天分享的内容是用微相E316、上位机和Matlab实现FM电台信号监听。注意本文仅用于科研和学习,私自搭建电台属于违法行为。 1.概述 微相E316、上位机和Matlab实现FM电台信号…

【总结】GraphRAG与传统RAG的深度对比及主流项目分析

GraphRAG和传统RAG的区别 GraphRAG和传统RAG都是为了增强大语言模型(LLMs)在特定领域的能力而发展出的技术,但它们在多个方面存在明显区别。 1. 知识组织方式 传统RAG:通常将大规模文本语料库分割成文本块,再利用嵌入…

SessionBox同一浏览器登录多账号独立IP教程

对于多账号运营的跨境营销人员来说,SessionBox提供了同一浏览器登录多账号的解决方案,但是很多人不仅需要多账号登录,对于登录Facebook、Instagram等账号来说,如何SessionBox与代理配合使用以确保真正的帐户分离更为重要&#xff…

图论 之 迪斯科特拉算法求解最短路径

文章目录 题目743.网络延迟时间3341.到达最后一个房间的最少时间I 求解最短路径的问题,分为使用BFS和使用迪斯科特拉算法,这两种算法求解的范围是有区别的 BFS适合求解,边的权值都是1的图中的最短路径的问题 图论 之 BFS迪斯科特拉算法适合求…

Docker+Dify部署DeepSeek-r1本地知识库

安装配置Docker Desktop 软件下载 Docker Desktop版本:4.38.0.181591 Docker Desktop下载地址:Docker: Accelerated Container Application Development 或者从这里下载:DockerDesktop-4.38.0.181591资源-CSDN文库 点击图下所示位置,下载windows-AMD64版本软件 启用Hy…

ubuntu ffmpeg 安装踩坑

ffmpeg 安装踩坑 安装命令: sudo apt update sudo apt install ffmpeg如果以上命令没有报错,那么恭喜你很幸运,可以关闭这篇文章了! 如果跟我一样,遇到如下报错,可以接着往下看: 报错信息: …

如何通过Windows环境远程控制MusicGPT在线生成高质量AI音乐

文章目录 前言1. 本地部署2. 使用方法介绍3. 内网穿透工具下载安装4. 配置公网地址5. 配置固定公网地址 前言 在这个快节奏的时代,音乐不仅是心灵的慰藉,更是创意的源泉。试想一下,在忙碌的工作间隙或悠闲的周末午后,只需轻敲几行…

大数据组件(四)快速入门实时数据湖存储系统Apache Paimon(3)

Paimon的下载及安装,并且了解了主键表的引擎以及changelog-producer的含义参考: 大数据组件(四)快速入门实时数据湖存储系统Apache Paimon(1) 利用Paimon表做lookup join,集成mysql cdc等参考: 大数据组件(四)快速入门实时数据…

Spring面试题2

1、compareable和compactor区别 定义与包位置:Comparable是一个接口,位于java.lang包,需要类去实现接口;而Compactor是一个外部比较器,位于java.util包 用法:Comparable只需要实现int compareTo(T o) 方法,比较当前对…

react(9)-redux

使用CRA快速创建react项目 npx create-react-app react-redux 安装配套工具 npm i reduxjs/toolkit react-redux 启动项目 在创建项目时候会出现一个问题 You are running create-react-app 5.0.0, which is behind the latest release (5.0.1). We no longer support…

HTTP SSE 实现

参考: SSE协议 SSE技术详解:使用 HTTP 做服务端数据推送应用的技术 一句概扩 SSE可理解为:服务端和客户端建立连接之后双方均保持连接,但仅支持服务端向客户端推送数据。推送完毕之后关闭连接,无状态行。 下面是基于…

STL —— 洛谷字符串(string库)入门题(蓝桥杯题目训练)(二)

目录 一、B2121 最长最短单词 - 洛谷 算法代码: 代码分析 变量定义 输入处理 单词长度计算 更新最长和最短单词的长度 输出最长单词 输出最短单词 评测记录:​编辑 二、B2122 单词翻转 - 洛谷 算法代码: 代码分析 引入头文件和定…

74. 搜索二维矩阵(LeetCode 热题 100)

题目来源; 74. 搜索二维矩阵 - 力扣(LeetCode) 题目内容: 给你一个满足下述两条属性的 m x n 整数矩阵: 每行中的整数从左到右按非严格递增顺序排列。 每行的第一个整数大于前一行的最后一个整数。 给你一个整数 target &am…

JUC并发—9.并发安全集合四

大纲 1.并发安全的数组列表CopyOnWriteArrayList 2.并发安全的链表队列ConcurrentLinkedQueue 3.并发编程中的阻塞队列概述 4.JUC的各种阻塞队列介绍 5.LinkedBlockingQueue的具体实现原理 6.基于两个队列实现的集群同步机制 4.JUC的各种阻塞队列介绍 (1)基于数组的阻塞…

SQL Server导出和导入可选的数据库表和数据,以sql脚本形式

一、导出 1. 打开SQL Server Management Studio,在需要导出表的数据库上单击右键 → 任务 → 生成脚本 2. 在生成脚本的窗口中单击进入下一步 3. 如果只需要导出部分表,则选择第二项**“选择具体的数据库对象(Select specific database objects)”**&am…

DDoCT:形态保持的双域联合优化用于快速稀疏视角低剂量CT成像|文献速递-医学影像人工智能进展

Title 题目 DDoCT: Morphology preserved dual-domain joint optimization for fast sparse-view low-dose CT imaging DDoCT:形态保持的双域联合优化用于快速稀疏视角低剂量CT成像 01 文献速递介绍 计算机断层扫描(CT)是当今广泛应用的…