简体   繁体   中英

Assign matrix element in OpenCV

What is the most generic way of assigning an element from one source matrix to a destination matrix in OpenCV? I always find myself coding something like this, which is not exactly elegant:

cv::Mat source; // CV_32FC3
cv::Mat dest;   // CV_32FC3

// ...

switch( source.channels() )
{
case 1:
    {
        dest.at<float>( y, x ) = source.at<float>( j, i );
        break;
    }
case 2:
    {
        dest.at<cv::Vec2f>( y, x ) = source.at<cv::Vec2f>( j, i );
        break;
    }
case 3:
    {
        dest.at<cv::Vec3f>( y, x ) = source.at<cv::Vec3f>( j, i );
        break; 
    }
case 4:
    {
        dest.at<cv::Vec4f>( y, x ) = source.at<cv::Vec4f>( j, i );
        break;
    }
}

I am wondering what the recommended way for this would be, there must be some generic one-liner for this, right?

Bonus points for a solution working across different data types (eg assigning n-channel float elements to n-channel double or short elements)

There is a templated version for cv::Vec<T, n> so you could make a template function taking source and destination types, as well as number of channels like so:

template<typename TSrc, typename TDst, int N>
void assign(const cv::Mat& src, cv::Mat& dst, int x, int y)
{
    assert(src.channels() == N);
    assert(dst.channels() == N);
    assert(src.size() == dst.size());

    const cv::Vec<TSrc, N>& srcVec = src.at<cv::Vec<TSrc, N>>(x, y);
    cv::Vec<TDst, N>& dstVec = dst.at<cv::Vec<TDst, N>>(x, y);
    for (int i = 0; i < N; ++i)
        dstVec[i] = static_cast<TDst>(srcVec[i]);
}
int main(int argc, char* argv[])
{   //sample usage:
    cv::Mat src(5, 5, CV_8UC3, cv::Scalar::all(255)), dst(5, 5, CV_32FC3, cv::Scalar::all(1));
    assign<unsigned char, float, 3>(src, dst, 3, 3);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM