2012-10-17 156 views
11

我想輸出一個藍色的手,但得到不正確的輸出。我在下面包含了輸入圖片,不正確的輸出圖片和代碼。OpenCV關閉一個形狀並填充它

我認爲下面的代碼不會填滿整個圖像,因爲圖像還沒有在右邊界處關閉。

如何關閉形狀並正確填充藍色?

close shape

#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp> 
#include <opencv2/imgproc/imgproc.hpp> 
#include <iostream> 
#include <stdio.h> 
#include <stdlib.h> 

using namespace cv; 
using namespace std; 

void drawStuff(); 
void showInputWindow(); 
void showCannyWindow(); 
void showContourWindow(); 

int thresh = 40; 
int max_thresh = 120; 
Mat img_rgb,img_gray,img_bw,canny_output,drawing; 

int main(){ 
    img_rgb = imread("qq.jpg"); 
    blur(img_rgb, img_rgb, Size(3,3)); 
    cvtColor(img_rgb,img_gray,CV_RGB2GRAY); 
    showInputWindow(); 

    drawStuff(); 
    cv::waitKey(0); 
} 

void drawStuff(){ 
    vector<vector<Point> > contours; 
    vector<Vec4i> hierarchy; 

    Canny(img_gray, canny_output, thresh, thresh*2, 3); 
    cv::dilate(canny_output, canny_output, cv::Mat(), cv::Point(-1,-1)); 
    showCannyWindow(); 

    findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); 
    drawing = Mat::zeros(canny_output.size(), CV_8UC3); 

    vector<Point> approxShape; 
    for(size_t i = 0; i < contours.size(); i++){ 
     approxPolyDP(contours[i], approxShape, arcLength(Mat(contours[i]), true)*0.04, true); 
     drawContours(drawing, contours, i, Scalar(255, 0, 0), CV_FILLED); // fill BLUE 
    } 

    showContourWindow(); 
} 

void showInputWindow(){ 
    cv::namedWindow("InputImage"); 
    cv::imshow("InputImage",img_rgb); 
} 

void showCannyWindow(){ 
    cv::namedWindow("Canny"); 
    cv::imshow("Canny",canny_output); 
} 
void showContourWindow(){ 
    cv::namedWindow("Fill"); 
    cv::imshow("Fill",drawing); 
} 
+2

我認爲問題在於手裏有輪廓。嘗試一種反向方法 - 填充周圍環境,然後倒轉。 –

+0

你如何填補周圍環境? –

+2

僅使用一些不同的顏色(如綠色)繪製輪廓(未填充),然後使用cvFloodFill播種在左上角(coords 0,0)並用藍色填充。然後行走圖像,用藍色取代黑色和黑色或綠色像素的藍色像素。 –

回答

6

解決你的問題,你應該只檢測外輪廓。通過這樣做,你將只能得到一個輪廓,並且可以用你的顏色填充它。

findContours(canny_output, contours, hierarchy, Imgproc.RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));