繁体   English   中英

在OpenCV C ++中遮罩彩色图像

[英]Mask color image in OpenCV C++

我有相同大小的黑白图像和彩色图像。 我想将它们组合在一起,以获得一张黑白图像为黑色的黑白图像,以及与黑白图像为白色的彩色图像相同的颜色。

这是C ++中的代码:

#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main(){
    Mat img1 = imread("frame1.jpg"); //coloured image
    Mat img2 = imread("framePr.jpg", 0); //grayscale image

    imshow("Oreginal", img1);

    //preform AND
    Mat r;
    bitwise_and(img1, img2, r);

    imshow("Result", r);

    waitKey(0);
    return 0;

}

这是错误消息:

OpenCV Error: Sizes of input arguments do not match (The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array') in binary_op, file /home/voja/src/opencv-2.4.10/modules/core/src/arithm.cpp, line 1021
terminate called after throwing an instance of 'cv::Exception'
  what():  /home/voja/src/opencv-2.4.10/modules/core/src/arithm.cpp:1021: error: (-209) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function binary_op

Aborted (core dumped)

首先,黑白图像与灰度图像不同。 两者都是Mat's类型CV_8U的。 但是灰度图像中的每个像素可以取0到255之间的任何值。二进制图像应该只有两个值-零和非零数。

其次, bitwise_and不能应用于不同类型的Mat's 灰度图像是CV_8U类型的单通道图像(每像素8位),彩色图像是CV_BGRA类型的3通道图像(每像素32位)。

看来您想要做的事情可以用口罩完成。

//threshold grayscale to binary image 
cv::threshold(img2 , img2 , 100, 255, cv::THRESH_BINARY);
//copy the color image with binary image as mask
img1.copyTo(r, img2);

实际上,使用img1作为copyTo掩码非常简单:

//Create a black colored image, with same size and type of the input color image
cv::Mat r = zeros(img2.size(),img2.type()); 
img1.copyTo(r, img2); //Only copies pixels which are !=0 in the mask

正如Kiran所说,由于bitwise_and无法对不同类型的图像进行操作,因此会出现错误。


正如Kiran指出的那样 ,初始分配和清零不是强制性的(但是,事前对性能没有影响)。 文档中

当指定了操作掩码时,如果上面显示的Mat :: create调用重新分配了矩阵,则在复制数据之前,将用全零初始化新分配的矩阵。

因此,整个操作可以通过以下简单操作完成:

img1.copyTo(r, img2); //Only copies pixels which are !=0 in the mask

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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