cv::Mat ptr 和 at 注意事项

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/seamanj/article/details/81263517

声明了一个cv::Mat cloud(1, 1000, CV_32FC4)

然后Point的定义如下

    struct Point
    {
        union
        {
            float data[4];
            struct { float x, y, z, w; };
        };
    };

然后我想取第i个point的指针

query = flann::Matrix<float>(reinterpret_cast<float*>(cloud.ptr<Point>(i)), 1, 3);

结果 是错误的
正确的方式 应该为

query = flann::Matrix<float>(reinterpret_cast<float*>(cloud.ptr<Point>(0, i)), 1, 3);

原来对于ptr来说只输入1个参数代码取第几行的地址

但是at就不一样了, 其实输入1个参数还是能返回正确的结果, 这是为什么呢?

看看opencv 的源码吧

template<typename _Tp> inline _Tp* Mat::ptr(int y)
{
    CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) );
    return (_Tp*)(data + step.p[0]*y);
}
template<typename _Tp> inline _Tp& Mat::at(int i0)
{
    CV_DbgAssert( dims <= 2 && data &&
                 (unsigned)i0 < (unsigned)(size.p[0]*size.p[1]) &&
                 elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
    if( isContinuous() || size.p[0] == 1 )
        return ((_Tp*)data)[i0];
    if( size.p[1] == 1 )
        return *(_Tp*)(data + step.p[0]*i0);
    int i = i0/cols, j = i0 - i*cols;
    return ((_Tp*)(data + step.p[0]*i))[j];
}

但是为什么第一个错误的调用没有触发

CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) );

很奇怪

另外

cloud.ptr<Point>(i)[j] = cloud.at<Point>(i,j)

猜你喜欢

转载自blog.csdn.net/seamanj/article/details/81263517
今日推荐