【问题标题】:Cannot assign any value greater 255 OpenCV无法分配任何大于 255 OpenCV 的值
【发布时间】:2021-12-20 19:45:19
【问题描述】:

我试图创建一个直方图,但我无法分配任何大于 255 的值,如果它超过示例 256,它将为 0,依此类推。我该如何解决?

    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)pColHistMatrix[0] << " ";
        }
    }

【问题讨论】:

  • 您使用的是 unsigned char,它通常只有 8 位,因此不能保存大于 255 的值
  • 我试过CV_16SC1,结果一样
  • 存储在矩阵中的数据类型是 16 位,但您正在转换为 uchar*
  • 非常感谢,祝您有美好的一天。新手太难了,我会尽快解决的
  • 首先你应该删除所有的指针算法并使用histMatrix.at&lt;short&gt;(i,j) 方法来访问矩阵...

标签: c++ opencv


【解决方案1】:

我为和我有同样错误的人提供解决方案

错误是 uchar* 只处理 8 位变量,当我们移动 n 字节时,我们必须为 sizeof(type) 分配,这里是 singed short

    histMatrix = Mat(nChannelSource, 256, CV_16SC1);

    signed short* pRowHistMatrix = (signed short*)histMatrix.data;
    for (int y = 0; y < nChannelSource; y++, pRowHistMatrix += histMatrix.step[0] / sizeof(signed short)) {
        signed short* pColHistMatrix = pRowHistMatrix;

        for (int x = 0; x < 256; x++, pColHistMatrix += histMatrix.step[1] / sizeof(signed short)) {
            pColHistMatrix[0] = 256;
        }
    }

【讨论】:

  • 这段代码中与问题代码非常相似的答案部分是什么?
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2019-04-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-21
相关资源
最近更新 更多