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

devtools/2025/2/25 7:48:04/

《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.ppmy.cn/devtools/161527.html

相关文章

GPU和FPGA的区别

GPU(Graphics Processing Unit,图形处理器)和 FPGA(Field-Programmable Gate Array,现场可编程门阵列)不是同一种硬件。 我的理解是,虽然都可以用于并行计算,但是GPU是纯计算的硬件…

Hadoop 基础原理

Hadoop 基础原理 基本介绍Hadoop 的必要性Hadoop 核心组件Hadoop 生态系统中的附加组件 HDFSHDFS 集群架构HDFS 读写流程HDFS 写流程HDFS 读流程 NameNode 持久化机制 MapReduce底层原理示例 Hadoop 是一个由 Apache 基金会开发的分布式系统基础架构,主要解决海量数…

WPF基本布局基础

一. Grid 描述: Grid 是WPF中最常用的布局容器之一。它允许你通过定义行和列来创建一个灵活的网格布局。子元素可以放置在特定的行和列中,并且可以跨越多行或多列。 特点: 支持行和列的定义,可以设置行高和列宽。 支持子元素的绝对定位和相对定位。 适…

让网页“浪“起来:打造会呼吸的波浪背景

每次打开那些让人眼前一亮的网页时,你是否有注意到那些看似随波逐流的动态背景?今天咱们不聊高深的技术,就用最朴素的CSS,来解锁这个让页面瞬间鲜活的秘籍。无需JavaScript,不用复杂框架,准备好一杯咖啡&am…

云原生周刊:云原生和 AI

开源项目推荐 FlashMLA DeepSeek 于北京时间 2025 年 2 月 24 日上午 9 点正式开源了 FlashMLA 项目。FlashMLA 是专为 NVIDIA Hopper 架构 GPU(如 H100、H800)优化的高效多头潜在注意力(MLA)解码内核,旨在提升大模型…

SSL和TLS:深入了解网络安全的基石

随着数据泄露和网络攻击事件的频繁发生,保护个人信息和敏感数据的需求愈发迫切。其中,SSL(安全套接层)和TLS(传输层安全协议)技术作为网络安全的重要组成部分,扮演了至关重要的角色。COCOSSL将通…

DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方DeepSeek接入)

前言 在当今数字化时代,AI编程助手已成为提升开发效率的利器。DeepSeek作为一款强大的AI模型,凭借其出色的性能和开源免费的优势,成为许多开发者的首选。今天,就让我们一起探索如何将DeepSeek接入PyCharm,实现高效、智…

深入剖析 Java Pinpoint:分布式系统性能分析的利器

在当今分布式系统广泛应用的技术环境下,确保系统的高性能和稳定性成为了开发与运维工作的核心挑战。Java Pinpoint作为一款强大的分布式系统性能分析工具,以其独特的设计和丰富的功能,为开发者和运维人员提供了全面的性能监控与故障排查解决方…