首页 > 解决方案 > 无法分配任何大于 255 OpenCV 的值

问题描述

我试图创建一个直方图,但我不能分配任何大于 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] << " ";
        }
    }

标签: c++opencv

解决方案


我为与我有相同错误的人提供解决方案

错误是 uchar* 只处理一个变量的 8 位,当我们将 n 字节移向我们必须为 sizeof(type) 分配时,这里是简短的

    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;
        }
    }

推荐阅读