2011-08-15 117 views
1

我是OpenCv的新手,並且已經將它用於小型項目。OpenCV中的反向填充圖像

我打算除了圖像內的一個矩形區域之外全部填充單個通道圖像。

我有兩個問題。

1)用黑色填充單個通道圖像。 (cvSet不會在單通道上工作)

2)除圖像內的矩形區域外,在圖像上執行填充。

任何解決方案?

+1

它是否必須是通用的?如果只是爲了一個小項目,我只需要使用兩個嵌套for循環,如果它在矩形內部進行測試,則會對if進行測試,並遍歷圖像。 – user786653

回答

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; 
} 
+0

雖然 – user786653

+0

灰度被指定在這個問題中,但似乎將圖像轉換爲灰度:_I打算在整個圖像中填充單個通道圖像,但圖像中的矩形區域除外。如果省略'CV_LOAD_IMAGE_GRAYSCALE',它也適用於彩色圖像從電話到'imread'。 – SSteve

+0

對不起,你是絕對正確的,出於某種原因,我把它解釋爲OP只想清除一個通道。 +1(附註爲其他人在Ubuntu上安裝'libcv-dev'和安裝好的朋友:在將包含內容更改爲簡單的''後,您需要使用'g ++ $(pkg-config opencv --cflags --libs) '和'') – user786653

0

嵌套for循環確實是最快的方法。

否則,請考慮製作一個使用cvZero(全黑)清除的相同大小的緩衝區。然後,將setROI設置爲您關心的區域,然後將cvCopy複製到臨時緩衝區中。

cvAnd的位掩碼也是一個不錯的和乾淨的解決方案。