cv::Mat_ to std::vector conversion

2019-09-02 07:00发布

问题:

I use OpenCV 2.0, there is a method in the cv::Mat_<_Tp> class:

// conversion to vector.
operator vector<_Tp>() const;

When instantiated, the implementation does not compile on MSVS 2005:

template<typename _Tp> inline Mat_<_Tp>::operator vector<_Tp>() const
{
    CV_Assert( rows == 1 || cols == 1 );
    return isContinuous() ? vector<_Tp>((size_t)(rows + cols - 1), (_Tp*)data) :
        (vector<_Tp>)((Mat_<_Tp>)this->t());
}

Is it a new fancy constructor of std::vector that takes size_t and _Tp* from TR1 or something?

I thought they could just initialize the vector by an iterator instead:

vector<_Tp>((_Tp*)data, (_Tp*)data + rows + cols - 1)

Is it a bug, or don't I know something?

UPD. Compiler error text:

...\lib\opencv\include\opencv\cxmat.hpp(691) : error C2665: 'std::vector<_Ty>::vector' : none of the 6 overloads could convert all the argument types
        with
        [
            _Ty=double
        ]
        c:\program files\microsoft visual studio 8\vc\include\vector(473): could be 'std::vector<_Ty>::vector(__w64 unsigned int,const _Ty &)'
        with
        [
            _Ty=double
        ]
        while trying to match the argument list '(size_t, double *)'
        ...\lib\opencv\include\opencv\cxmat.hpp(689) : while compiling class template member function 'cv::Mat_<_Tp>::operator std::vector<_Ty>(void) const'
        with
        [
            _Tp=double,
            _Ty=double
        ]
        z:\dev\mine\temp\temp\entry.cpp(37) : see reference to class template instantiation 'cv::Mat_<_Tp>' being compiled
        with
        [
            _Tp=double
        ]

回答1:

No, there are new constructors from rvalues in C++0x, but nothing like the one used here.

If isContinuous() means that all vales are the same, you could possibly use vector<_Tp>((size_t)(rows + cols - 1), *(_Tp*)data) to make copies of the first value.

Your iterator version seems correct otherwise.