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

如何在OpenCV图像上绘制2D高斯斑点?现有代码异常求助

问题:OpenCV实现CenterNet高斯Heatmap失败,输出全黑

需求

  • 生成椭圆高斯斑点(可自定义宽高)
  • 指定斑点在目标图像中的中心点位置
  • 斑点中心像素值为255,向边缘平滑渐变至0
  • 无需支持旋转
    最终效果为椭圆高斯热图,用于CenterNet模型训练。

现有代码运行后生成的图像全空白,高斯斑点的最大值仅为1e-11量级,缩放后全部为0。


错误原因分析

  1. 坐标系统混淆:生成局部网格时,x、y是0-1范围的局部坐标,但计算高斯分布时错误使用了全局图像的中心坐标(1000,400),导致偏移量极大,指数运算后结果趋近于0。
  2. 高斯参数设置错误:未匹配斑点尺寸设置合理的sigma参数,导致分布范围与斑点大小不匹配。

修正后的代码

import numpy as np
import cv2

def main():
    np.set_printoptions(suppress=True)

    hm_width = 1600
    hm_height = 1000

    # 创建空白热图(OpenCV格式,HxW)
    heatmap = np.zeros((hm_height, hm_width), dtype=np.uint8)

    # 高斯斑点参数
    blob_height = 100
    blob_width = 300
    blob_center_x = 1000  # 热图中的全局x坐标
    blob_center_y = 400   # 热图中的全局y坐标

    # 生成局部网格坐标(0到1的归一化范围)
    x, y = np.meshgrid(np.linspace(0, 1, blob_width), np.linspace(0, 1, blob_height))
    
    # 计算局部坐标到斑点中心的偏移(局部中心为(0.5, 0.5))
    x_offset = x - 0.5
    y_offset = y - 0.5

    # 设置高斯sigma:CenterNet标准配置,3倍sigma覆盖整个斑点
    sigma_x = blob_width / 6
    sigma_y = blob_height / 6

    # 计算高斯分布值,中心为1,边缘趋近于0
    gaussian_blob = np.exp(-( (x_offset * blob_width)**2 / (2 * sigma_x**2) + 
                             (y_offset * blob_height)**2 / (2 * sigma_y**2) ))

    # 缩放至0-255范围并转换为uint8类型
    gaussian_blob = (gaussian_blob * 255).astype(np.uint8)

    # 计算斑点在热图中的位置,避免越界
    blob_left = int(blob_center_x - blob_width / 2)
    blob_right = blob_left + blob_width
    blob_top = int(blob_center_y - blob_height / 2)
    blob_bottom = blob_top + blob_height

    # 边界校验,防止超出热图范围
    blob_left = max(0, blob_left)
    blob_right = min(hm_width, blob_right)
    blob_top = max(0, blob_top)
    blob_bottom = min(hm_height, blob_bottom)

    # 截取斑点中对应热图的有效区域
    crop_blob = gaussian_blob[:(blob_bottom - blob_top), :(blob_right - blob_left)]

    # 将高斯斑点赋值到热图对应位置
    heatmap[blob_top:blob_bottom, blob_left:blob_right] = crop_blob

    # 显示结果
    cv2.imshow('Gaussian Blob', gaussian_blob)
    cv2.imshow('Heatmap', heatmap)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

关键修正点

  • 坐标系统对齐:使用局部网格的中心(0.5,0.5)作为高斯分布的中心,避免与全局坐标混淆。
  • Sigma参数适配:采用CenterNet常用的sigma = 目标尺寸/6,确保3倍sigma覆盖整个斑点,边缘值自然衰减至0。
  • 边界越界处理:添加边界校验逻辑,防止斑点超出热图范围导致赋值错误。
  • 数值优化:直接将高斯值(0-1区间)缩放至0-255,保证中心像素值为255。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:36:01