【问题标题】:Create mask from color Image in C++ (Superimposing a colored image mask)在 C++ 中从彩色图像创建蒙版(叠加彩色图像蒙版)
【发布时间】:2015-07-09 09:52:56
【问题描述】:

我编写了一个实时检测正方形(白色)并在其周围绘制框架的代码。正方形长度为 l 的每一边被分成 7 个部分。然后我在从垂直于三角形边(蓝色)的偏差演变而来的六个点上画一条长度为 h=l/7 的线。角标为红色。然后看起来像这样:

为了绘制蓝线和圆圈,我有一个 3 通道 (CV_8UC3) 矩阵 drawing,除了红线、蓝线和白线的位置外,其他所有位置都为零。然后我将这个矩阵放在我的网络摄像头图像上的方法是使用 opencv 的addWeighted 函数。 addWeighted( drawing, 1, webcam_img, 1, 0.0, dst); (Description for addWeighted here)。 但是,正如您所看到的,我得到的效果是,我的破折号和圆圈的颜色在黑色区域之外是错误的(在黑色区域内可能也不正确,但在那里更好)。它为什么会发生是完全有道理的,因为它只是将矩阵与权重相加。

我希望矩阵drawing 在我的图像上具有正确的颜色。问题是,我不知道如何解决它。我不知何故需要一个面具drawing_mask,我的破折号在某种程度上叠加到我的相机图像上。在 Matlab 中类似于 dst=webcam_img; dst(drawing>0)=drawing(drawing>0);

有人知道如何在 C++ 中执行此操作吗?

【问题讨论】:

    标签: c++ algorithm opencv image-processing mask


    【解决方案1】:

    1。自定义版本

    我会明确写出来:

    const int cols = drawing.cols;
    const int rows = drawing.rows;
    
    for (int j = 0; j < rows; j++) {
        const uint8_t* p_draw = drawing.ptr(j); //Take a pointer to j-th row of the image to be drawn
        uint8_t* p_dest = webcam_img.ptr(j);  //Take a pointer to j-th row of the destination image
        for (int i = 0; i < cols; i++) {
            //Check all three channels BGR
            if(p_draw[0] | p_draw[1] | p_draw[2]) { //Using binary OR should ease the optimization work for the compiler
                p_dest[0] = p_draw[0]; //If the pixel is not zero, 
                p_dest[1] = p_draw[1]; //copy it (overwrite) in the destination image
                p_dest[2] = p_draw[2];
            }
            p_dest += 3; //Move to the next pixel
            p_draw += 3; 
        }
    }
    

    当然,您可以将此代码移动到带有参数(const cv::Mat&amp; drawing, cv::Mat&amp; webcam_img) 的函数中。

    2。 OpenCV“纯粹”版本

    但纯粹的 OpenCV 方式如下:

    cv::Mat mask;
    //Create a single channel image where each pixel != 0 if it is colored in your "drawing" image
    cv::cvtColor(drawing, mask, CV_BGR2GRAY);
     //Copy to destination image only pixels that are != 0 in the mask
    drawing.copyTo(webcam_img, mask);
    

    效率较低(创建蒙版的颜色转换有点昂贵),但肯定更紧凑。小提示:如果你有一种很深的颜色,比如(0,0,1),它会在灰度中转换为0


    另请注意,在目标图像中重绘相同的叠加层(线、圆)可能会更便宜,基本上调用与创建 drawing 图像相同的绘制操作。

    【讨论】:

    • 完美运行,非常感谢。我在一个函数中实现了你的第一个解决方案。这工作得很好。然后我读了你的最后一条笔记,然后将我的叠加层重绘为webcam_img。这可能是我要说的最快和最简单的解决方案。太好了谢谢。 SemtexB
    猜你喜欢
    • 1970-01-01
    • 2012-05-15
    • 2023-03-04
    • 1970-01-01
    • 2017-11-16
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多