OpenCV中的反向填充图像

时间:2011-08-15 11:44:16

标签: c image-processing opencv

我是OpenCv的新手,并且已经将它用于一个小项目。

除了图像中的矩形区域外,我打算全部填充单个通道图像。

我有两个问题。

1)用黑色填充单个通道图像。 (cvSet不能在单通道上工作)

2)除了图像中的矩形区域外,在整个图像上进行填充。

任何解决方案?

2 个答案:

答案 0 :(得分:3)

这是一个程序,显示如何用黑色填充单个通道,以及如何使用蒙版将图像设置为黑色。

#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

int main(int argc, const char * argv[]) {

    cv::Mat image;
    image = cv::imread("../../lena.jpg", CV_LOAD_IMAGE_GRAYSCALE);

    if (!image.data) {
        std::cout << "Image file not found\n";
        return 1;
    }

    cv::namedWindow("original");
    cv::imshow("original", image);

    //Define the ROI rectangle
    cv::Rect ROIrect(100, 100, 200, 200);

    //Create a deep copy of the image
    cv::Mat fill(image.clone());
    //Specify the ROI
    cv::Mat fillROI = fill(ROIrect);
    //Fill the ROI with black
    fillROI = cv::Scalar(0);

    cv::namedWindow("fill");
    cv::imshow("fill", fill);
    cvMoveWindow("fill", 500, 40);

    //create a deep copy of the image
    cv::Mat inverseFill(image.clone());
    //create a single-channel mask the same size as the image filled with 1
    cv::Mat inverseMask(inverseFill.size(), CV_8UC1, cv::Scalar(1));
    //Specify the ROI in the mask
    cv::Mat inverseMaskROI = inverseMask(ROIrect);
    //Fill the mask's ROI with 0
    inverseMaskROI = cv::Scalar(0);
    //Set the image to 0 in places where the mask is 1
    inverseFill.setTo(cv::Scalar(0), inverseMask);

    cv::namedWindow("inverseFill");
    cv::imshow("inverseFill", inverseFill);
    cvMoveWindow("inverseFill", 1000, 40);
    // wait for key
    cv::waitKey(0);

    return 0;
}

答案 1 :(得分:0)

嵌套for循环确实是最快捷的方式。

否则,请考虑使用cvZero(全黑)清除相同大小的缓冲区。然后,将setROI放到您关心的区域,并将cvCopy放入临时缓冲区。

使用cvAnd的位掩码也是一个很好的干净解决方案。