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

OpenCV创建直方图时无法赋值大于255的数值该如何解决?

问题根因
  • 你声明的矩阵类型为CV_16SC1,每个元素是16位有符号短整型,占2字节存储空间。你赋值256时,对应16位二进制为0x0100,低字节存储值为0、高字节存储值为1。
  • 输出时你直接读取pColHistMatrix[0],仅拿到了该元素的第一个低字节,所以会输出0,并不是赋值时数值溢出,而是读取逻辑错误。
修复方案

两种可选修复方式,第二种更简洁不易出错:

方案1:修正指针读写逻辑

保持原有指针访问方式,输出时同步做类型强转即可:

histMatrix = Mat(nChannelSource, 256, CV_16SC1);
uchar* pRowHistMatrix = histMatrix.data;
for (int y = 0; y < nChannelSource; y++, pRowHistMatrix += histMatrix.step[0]) {
    uchar* pColHistMatrix = pRowHistMatrix;
    for (int x = 0; x < 256; x++, pColHistMatrix += histMatrix.step[1]) {
        ((signed short*)pColHistMatrix)[0] = 256;
    }
}

pRowHistMatrix = histMatrix.data;
for (int y = 0; y < nChannelSource; y++, pRowHistMatrix += histMatrix.step[0]) {
    uchar* pColHistMatrix = pRowHistMatrix;
    for (int x = 0; x < 256; x++, pColHistMatrix += histMatrix.step[1]) {
        // 输出时先强转为对应类型指针再取值
        std::cout << (int)*((signed short*)pColHistMatrix) << " ";
    }
}

方案2:使用OpenCV自带的at方法访问元素

无需手动计算步长,避免类型转换错误:

histMatrix = Mat(nChannelSource, 256, CV_16SC1);
for (int y = 0; y < nChannelSource; y++) {
    for (int x = 0; x < 256; x++) {
        histMatrix.at<short>(y, x) = 256;
    }
}

for (int y = 0; y < nChannelSource; y++) {
    for (int x = 0; x < 256; x++) {
        std::cout << (int)histMatrix.at<short>(y, x) << " ";
    }
}

如果后续直方图统计的数值可能超过16位有符号整型最大值32767,可以把矩阵类型替换为CV_32SC1,对应访问时使用int类型即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:06:03