You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正Matplotlib中边界框与正方形的对齐问题?

修正Matplotlib中Rectangle与imshow的坐标系对齐问题

你遇到的对齐问题源于坐标系逻辑混淆:imshow默认使用左上角为原点(origin='upper'),而你手动反转y轴后,未同步调整Rectangle的y坐标计算逻辑。以下是两种直接可行的修正方案:

方案1:保留imshow默认坐标系(推荐)

直接移除y轴反转代码,让imshow的默认坐标系与Rectangle的坐标逻辑匹配:

修改后的核心代码片段:

# 绘制带边界框的图像
ax[2].imshow(img, cmap='gray')
x, y, width, height = bbox
# 直接使用原bbox坐标创建Rectangle,无需额外调整
rect = Rectangle((x, y), width, height, linewidth=2, edgecolor='r', facecolor='none')
ax[2].add_patch(rect)
ax[2].set_title('Image with Bounding Box')

# 移除y轴反转的代码
# for a in ax:
#     a.set_ylim([size, 0])  # Reverse y-axis to match array indexing

方案2:保留y轴反转(匹配数组索引方向)

如果需要让坐标轴y方向与数组索引一致(y=0对应图像顶部),则需调整Rectangle的y坐标,将数组行索引转换为反转后的轴坐标:

修改后的核心代码片段:

# 绘制带边界框的图像
ax[2].imshow(img, cmap='gray')
x, y, width, height = bbox
# 调整y坐标:反转后轴的y起始位置 = 图像尺寸 - 数组起始行索引 - 正方形高度
rect = Rectangle((x, size - y - height), width, height, linewidth=2, edgecolor='r', facecolor='none')
ax[2].add_patch(rect)
ax[2].set_title('Image with Bounding Box')

# 保留y轴反转代码
for a in ax:
    a.set_ylim([size, 0])  # Reverse y-axis to match array indexing

完整修正后的代码(方案1版本)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

def generate_square_image(size, square_size, noise_level=0.0):
    """
    Generates an image with a white square in the center.

    Args:
        size (int): The size of the image (size x size).
        square_size (int): The size of the square.
        noise_level (float): Standard deviation of Gaussian noise.

    Returns:
        numpy.ndarray: The image as a numpy array.
        numpy.ndarray: The mask.
        tuple: Bounding box (x_min, y_min, width, height).
    """

    # 创建掩码
    mask = np.zeros((size, size))
    start = (size - square_size) // 2
    end = start + square_size
    mask[start:end, start:end] = 1

    # 创建边界框
    bbox = (start, start, square_size, square_size)

    # 创建带噪图像
    img = mask.copy()
    if noise_level > 0:
        noise = np.random.normal(0, noise_level, img.shape)
        img = np.clip(img + noise, 0, 1)

    return img, mask, bbox

# 示例使用
size = 100
square_size = 40
img, mask, bbox = generate_square_image(size, square_size, noise_level=0.1)

# 绘图
fig, ax = plt.subplots(1, 3, figsize=(15, 5))
ax[0].imshow(img, cmap='gray')
ax[0].set_title('Generated Image')
ax[1].imshow(mask, cmap='gray')
ax[1].set_title('Mask')

# 绘制带边界框的图像
ax[2].imshow(img, cmap='gray')
x, y, width, height = bbox
rect = Rectangle((x, y), width, height, linewidth=2, edgecolor='r', facecolor='none')
ax[2].add_patch(rect)
ax[2].set_title('Image with Bounding Box')

plt.tight_layout()
plt.show()

内容的提问来源于stack exchange,提问作者Academic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:52:33