Mat 通道上的高效按位与

问题描述 投票:0回答:1

我需要对矩阵的所有 (3) 个通道进行按位与运算 并尝试了这种方式:

Mat img(5,5,CV_8UC3);
Mat chTmp, chRes;

extractChannel(img, chTmp, 0);
extractChannel(img, chRes, 1);
bitwise_and(chTmp, chRes, chRes);
extractChannel(img, chTmp, 2);
bitwise_and(chTmp, chRes, chRes);

但是 extractChannel 似乎分配/复制(?)通道的内容, 这是昂贵的。

有更好的方法吗?例如。构建 chRes 时仅访问/寻址 3 个通道,没有 tmp 通道?

c++ opencv mat
1个回答
0
投票

也许,使用

cv::Mat::reshape()
就能避免复制。 但我不知道这是否有效。

cv::Mat Src( 2,2, CV_8UC3 );
Src.at<cv::Vec3b>( 0,0 ) = cv::Vec3b( 0b0000'0000u, 0b0000'0001u, 0b0000'0010u );   // result should be 0000'0000 (=0)
Src.at<cv::Vec3b>( 0,1 ) = cv::Vec3b( 0b0000'1000u, 0b1000'1001u, 0b0000'1010u );   // result should be 0000'1000 (=8)
Src.at<cv::Vec3b>( 1,0 ) = cv::Vec3b( 0b1111'0000u, 0b0111'1001u, 0b0011'0000u );   // result should be 0011'0000 (=48)
Src.at<cv::Vec3b>( 1,1 ) = cv::Vec3b( 0b1111'1111u, 0b1111'1111u, 0b1111'1110u );   // result should be 1111'1110 (=254)

cv::Mat Result;
{
    cv::Mat Src_ = Src.reshape( 1, 2*2 );
    cv::Mat Result_;
    cv::bitwise_and( Src_.col(0), Src_.col(1), Result_ );
    cv::bitwise_and( Src_.col(2), Result_, Result_ );
    Result = Result_.reshape( 1, 2 );
}

std::cout << Result << std::endl;  //(output is [0,8; 48,254])
© www.soinside.com 2019 - 2024. All rights reserved.