OpenCV C++: how access pixel value CV_32F through uchar data pointer

前端 未结 2 1451
遇见更好的自我
遇见更好的自我 2020-12-09 06:17

Briefly, I would like to know if it is possible to directly access pixel value of a CV_32F Mat, through Mat member \"uchar* data\".

I can do it with no problem if Ma

相关标签:
2条回答
  • 2020-12-09 06:42

    Note that CV_32F means the elements are float instead of uchar. The "F" here means "float". And the "U" in CV_8U stands for unsigned integer. Maybe that's why your code doesn't give the right value. By declaring p as uchar*, p[4*B.step+5] makes p move to the fifth row and advance sizeof(uchar)*5, which tend to be wrong. You can try

    float value = (float) p[4*B.step + 5*B.elemSize()]
    

    but I'm not sure if it will work. Here are some ways to pass the data of [i, j] to value:

    1. value = B.at<float>(i, j)
    2. value = B.ptr<float>(i)[j]
    3. value = ((float*)B.data)[i*B.step+j]

    The 3rd way is not recommended though, since it's easy to overflow. Besides, a 6x5 matrix should be created by B.create(6, 5, CV_32FC1), I think?

    0 讨论(0)
  • 2020-12-09 06:56

    You can use ptr method which returns pointer to matrix row:

    for (int y = 0; y < mat.rows; ++y)
    {
        float* row_ptr = mat.ptr<float>(y);
        for (int x = 0; x < mat.cols; ++x)
        {
            float val = row_ptr[x];
        }
    }
    

    You can also cast data pointer to float and use elem_step instead of step if matrix is continous:

    float* ptr = (float*) mat.data;
    size_t elem_step = mat.step / sizeof(float);
    float val = ptr[i * elem_step + j];
    
    0 讨论(0)
提交回复
热议问题