Args:
bboxes: Tensor of bboxes [N,4] in xyxy format
Returns:
"""
w = bboxes[:, 2] - bboxes[:, 0]
h = bboxes[:, 3] - bboxes[:, 1]
return w * h
def centernet_gaussian_2d(shape, sigma=1.0):
m, n = [(ss - 1.0) / 2.0 for ss in shape]
y, x = np.ogrid[-m : m + 1, -n : n + 1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps * h.max()] = 0
return h
def centernet_circle_2d(r: int, value: float, dtype):
a, b = r, r
n = 2 * r + 1
y, x = np.ogrid[-a : n - a, -b : n - b]
mask = x * x + y * y <= r * r
array = np.zeros((n, n), dtype=dtype)
value = np.array(value, dtype=dtype).reshape((1, 1))
array[:] = value
array[~mask] = 0
return array
def compute_phi(w, h):
a, b = min(w, h), max(w, h)
aspect_ratio = a / b
angle = 45 * aspect_ratio
if w > h:
angle = 90 - angle
return angle
def bes_radius(det_size, min_overlap=0.5) -> int:
"""Compute radius of gaussian.
Arguments:
w (int): weight of box.
h (int): height of box.
iou_threshold (float): min required IOU between gt and smoothed box.
Returns:
radius (int): radius of gaussian.
"""
w, h = det_size
phi = compute_phi(w, h)
sin_phi = math.sin(math.radians(phi))
cos_phi = math.cos(math.radians(phi))
a = sin_phi * cos_phi
b = -(w * sin_phi + h * cos_phi)
c = w * h * (1 - min_overlap) / (1 + min_overlap)
d = math.sqrt(b * b - 4 * a * c)
r = -(b + d) / (2 * a)
return int(max(1, math.ceil(r)))
def one_hot_labels(tensor, num_classes: int):
"""Encodes class labes as one-hot vector. Negative labels converted too background class.
:param tensor: Labels vector of shape [N]
:param num_classes: Number of classes, including dummy background class. E.g num_real_classes + 1
:return: Labels tensor of shape [N, num_classes]
"""
if len(tensor) == 0:
return torch.from_numpy(np.array([], dtype=int)).long()
tensor = tensor.clone()
tensor[tensor < 0] = 0
one_hot_tensor = torch.zeros(tensor.size() + torch.Size([num_classes]))
dim = len(tensor.size())
index = tensor.unsqueeze(dim)
return one_hot_tensor.scatter_(dim, index, 1)
def change_box_order(boxes, order, dim=-1):
"""Change box order between (x_min, y_min, x_max, y_max) and (x_center, y_center, width, height).
Args:
boxes: (tensor) bounding boxes, sized [N, 4].
order: (str) either 'xyxy2xywh' or 'xywh2xyxy'.
Returns:
(tensor) converted bounding boxes, sized [N, 4].
"""
assert order in ["xyxy2xywh", "xywh2xyxy"]
a = boxes[..., 0:2]
b = boxes[..., 2:4]
if order == "xyxy2xywh":
return torch.cat([(a + b) / 2, b - a], dim)
return torch.cat([a - b / 2, a + b / 2], dim)
Args:
boxes: (tensor) bounding boxes of (x_min, y_min, x_max, y_max), sized [N, 4].
x_min: (number) min value of x.
y_min: (number) min value of y.
x_max: (number) max value of x.
y_max: (number) max value of y.
Returns:
(tensor) clamped boxes.
"""
boxes[:, 0] = boxes[:, 0].clamp(min=x_min, max=x_max)
boxes[:, 1] = boxes[:, 1].clamp(min=y_min, max=y_max)
boxes[:, 2] = boxes[:, 2].clamp(min=x_min, max=x_max)
boxes[:, 3] = boxes[:, 3].clamp(min=y_min, max=y_max)
return boxes
def box_select(boxes, x_min, y_min, x_max, y_max):
"""Select boxes in range (x_min, y_min, x_max, y_max).
Args:
boxes: (tensor) bounding boxes of (x_min, y_min, x_max, y_max), sized [N, 4].
x_min: (number) min value of x.
y_min: (number) min value of y.
x_max: (number) max value of x.
y_max: (number) max value of y.
Returns:
(tensor) selected boxes, sized [M, 4].
(tensor) selected mask, sized [N, ].
"""
mask = (boxes[:, 0] >= x_min) & (boxes[:, 1] >= y_min) & (boxes[:, 2] <= x_max) & (boxes[:, 3] <= y_max)
boxes = boxes[mask, :]
return boxes, mask
def box_iou(box1, box2):
"""Compute the intersection over union of two set of boxes.
def generate_yolo_targets(self, centers, confidences, is_vessel, is_fishing, lengths, grid_height, grid_width):
num_objects = len(centers)
yolo_targets = np.zeros((grid_height, grid_width, 6), dtype=np.float32) # Should have the right shape
for i in range(num_objects):
center = centers[i]
confidence = self.confidence_mapping[confidences[i]]
vessel_type = self.vessel_mapping.get(is_vessel[i], self.ignore_value)
fishing_status = self.fishing_mapping.get(is_fishing[i], self.ignore_value)
length = lengths[i]
grid_x = int(center[0] * grid_width)
grid_y = int(center[1] * grid_height)
# Ensure grid indices are within bounds
grid_x = min(grid_x, grid_width - 1)
grid_y = min(grid_y, grid_height - 1)
# Assign the values
yolo_targets[grid_y, grid_x, 0:4] = torch.tensor([center[0], center[1], length, length], dtype=torch.float32)
yolo_targets[grid_y, grid_x, 4] = confidence
yolo_targets[grid_y, grid_x, 5] = vessel_type # Make sure to assign the correct vessel type
return yolo_targets
To effectively use the generate_yolo_targets method in your YOLOHead class, it's crucial to correctly define the grid_height and grid_width parameters. These parameters typically correspond to the spatial dimensions of the feature map produced by the backbone network (e.g., after a series of convolutional and pooling layers) and are derived based on the input image size and the model's architecture (specifically, the stride of the network).
Here's a comprehensive guide to defining grid_height and grid_width and integrating them with your generate_yolo_targets method:
1. Understanding Grid Dimensions
In YOLO-based architectures, the input image is divided into a grid where each cell is responsible for predicting bounding boxes and class probabilities. The size of this grid (grid_height and grid_width) depends on:
Input Image Size: The resolution of the images fed into the network (e.g., 640x640).
Model's Stride: How much the input image is downsampled by the network. For example, a stride of 32 means the feature map is reduced by a factor of 32 in both height and width.
Example:
Input Image Size: 640x640
Stride: 32
Feature Map Dimensions: 640 / 32 = 20
Therefore, grid_height = grid_width = 20
2. Defining Grid Dimensions
You can calculate grid_height and grid_width based on the input image size and the stride of your YOLO model. Here's how you can do it:
a. Determine the Stride
First, ascertain the stride of your YOLO model. Common strides in YOLO architectures are 8, 16, 32, etc., corresponding to different scales (e.g., small, medium, large objects).
Alternatively, if your model processes images with dynamic sizes or multiple scales, you might need to determine the grid size dynamically based on the feature map dimensions output by the backbone network.
c. Integrate into the YOLOHead Class
You can modify the YOLOHead class to calculate grid_height and grid_width internally or pass them as parameters during initialization.
import torch
import torch.nn as nn
import numpy as np
from typing import List, Tuple
class YOLOHead(nn.Module):
def __init__(self, num_classes: int, anchors: List[Tuple[int, int]], input_image_size=(640, 640), stride=32):
super(YOLOHead, self).__init__()
self.num_classes = num_classes
self.anchors = anchors
self.num_anchors = len(anchors)
self.stride = stride
self.input_image_size = input_image_size
self.grid_height = input_image_size[0] // stride
self.grid_width = input_image_size[1] // stride
self.out_channels = self.num_anchors * (5 + self.num_classes) # (4 bbox + 1 confidence + classes)
# Define the convolutional layers
self.reg_conv = nn.Conv2d(256, 4 * self.num_anchors, kernel_size=1) # Ensure input channels match
self.obj_conv = nn.Conv2d(256, self.num_anchors, kernel_size=1)
self.cls_conv = nn.Conv2d(256, self.num_classes * self.num_anchors, kernel_size=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Forward pass for YOLOHead."""
cls_pred = self.cls_conv(x)
reg_pred = self.reg_conv(x)
obj_pred = self.obj_conv(x)
return torch.cat([reg_pred, obj_pred, cls_pred], dim=1)
def generate_yolo_targets(self, centers, confidences, is_vessel, is_fishing, lengths):
num_objects = len(centers)
yolo_targets = np.zeros((self.grid_height, self.grid_width, 6), dtype=np.float32) # Should have the right shape
for i in range(num_objects):
center = centers[i]
confidence = self.confidence_mapping[confidences[i]]
vessel_type = self.vessel_mapping.get(is_vessel[i], self.ignore_value)
fishing_status = self.fishing_mapping.get(is_fishing[i], self.ignore_value)
length = lengths[i]
grid_x = int(center[0] * self.grid_width)
grid_y = int(center[1] * self.grid_height)
# Ensure grid indices are within bounds
grid_x = min(grid_x, self.grid_width - 1)
grid_y = min(grid_y, self.grid_height - 1)
# Assign the values
yolo_targets[grid_y, grid_x, 0:4] = [center[0], center[1], length, length]
yolo_targets[grid_y, grid_x, 4] = confidence
yolo_targets[grid_y, grid_x, 5] = vessel_type # Make sure to assign the correct vessel type
return yolo_targets
3. Using Utility Functions from functional.py
If you need to dynamically compute grid sizes or perform related operations, you can utilize utility functions from your functional.py file. For example, meshgrid can help generate coordinate grids corresponding to your feature map.
Example: Creating a Meshgrid
from functional import meshgrid
class YOLOHead(nn.Module):
# ... [other parts of the class] ...
def generate_meshgrid(self):
return meshgrid(self.grid_width, self.grid_height, row_major=True) # Adjust `row_major` as needed
This meshgrid can be useful for certain operations like assigning target values or decoding predictions.
4. Ensuring Consistent Data Flow
Make sure that:
Input Images: The input images fed into the network match the expected input_image_size. If you resize images during preprocessing, update input_image_size accordingly.
Stride Consistency: The stride used to calculate grid_height and grid_width matches the actual downsampling performed by your network's architecture. Mismatched strides can lead to incorrect target assignments.
Target Generation: When generating targets using generate_yolo_targets, ensure that the center coordinates are normalized (e.g., between 0 and 1) relative to the input image size. This allows accurate mapping to the grid.
5. Example Usage
Here's how you might integrate everything in your training loop or data preprocessing pipeline:
# Define model parameters
num_classes = 20 # Example number of classes
anchors = [(10,13), (16,30), (33,23)] # Example anchor boxes
input_image_size = (640, 640)
stride = 32
# Initialize YOLOHead
yolo_head = YOLOHead(num_classes, anchors, input_image_size, stride)
# Example data
centers = [(0.5, 0.5), (0.3, 0.7)] # Normalized center coordinates
confidences = [0.9, 0.75]
is_vessel = [1, 0]
is_fishing = [1, 1]
lengths = [20, 15]
# Generate targets
yolo_targets = yolo_head.generate_yolo_targets(centers, confidences, is_vessel, is_fishing, lengths)
print("YOLO Targets Shape:", yolo_targets.shape) # Should be (20, 20, 6)
6. Additional Recommendations
Validation: Always validate that grid_height and grid_width correctly correspond to your model's feature map dimensions. Mismatches can lead to incorrect target assignments and degraded model performance.
Dynamic Grid Sizes: If you're dealing with multiple feature maps (e.g., different scales in Feature Pyramid Networks), ensure that you correctly define grid sizes for each scale.
Debugging: Visualize the yolo_targets to ensure that targets are being assigned correctly on the grid. This can help in identifying issues related to grid size calculations or target assignments.
7. Potential Code Corrections
While reviewing your generate_yolo_targets function, I noticed that you're assigning a torch.tensor to a NumPy array. To maintain consistency, consider using NumPy arrays throughout or convert yolo_targets to a PyTorch tensor before assignment.
Example Correction:
def generate_yolo_targets(self, centers, confidences, is_vessel, is_fishing, lengths):
num_objects = len(centers)
yolo_targets = np.zeros((self.grid_height, self.grid_width, 6), dtype=np.float32) # Initialize as NumPy array
for i in range(num_objects):
center = centers[i]
confidence = self.confidence_mapping[confidences[i]]
vessel_type = self.vessel_mapping.get(is_vessel[i], self.ignore_value)
fishing_status = self.fishing_mapping.get(is_fishing[i], self.ignore_value)
length = lengths[i]
grid_x = int(center[0] * self.grid_width)
grid_y = int(center[1] * self.grid_height)
# Ensure grid indices are within bounds
grid_x = min(grid_x, self.grid_width - 1)
grid_y = min(grid_y, self.grid_height - 1)
# Assign the values
yolo_targets[grid_y, grid_x, 0:4] = [center[0], center[1], length, length]
yolo_targets[grid_y, grid_x, 4] = confidence
yolo_targets[grid_y, grid_x, 5] = vessel_type # Assign the correct vessel type
return torch.from_numpy(yolo_targets) # Convert to PyTorch tensor if needed
Alternatively, initialize yolo_targets as a PyTorch tensor:
Defining grid_height and grid_width accurately is fundamental to the success of your YOLO-based object detection model. By calculating these dimensions based on your input image size and the network's stride, and ensuring consistency throughout your data pipeline, you'll set a strong foundation for effective target generation and model training.
If you have further questions or need assistance with specific parts of your implementation, feel free to ask!