2016-04-21 141 views
0

我是OpenCV的新手,希望能夠在我正在進行的項目中獲得幫助。我想要將前景與背景分開,並調整/裁剪原始圖像以使前景適合。使用Opencv調整圖像大小/裁剪圖像

我有這個樣,我想能夠得到這樣一個最佳結果:

以前
enter image description here


enter image description here

回答

1

簡單代碼只是爲了給出一個想法。它適用於像你這樣的圖像。

(注:我用這個code部分)

#include "opencv2/opencv.hpp" 

using namespace cv; 
using namespace std; 

int main(int argc, char** argv) 
{ 
    int largest_area=0; 
    int largest_contour_index=0; 
    cv::Rect bounding_rect; 

    Mat src = imread(argv[1]); 
    Mat edges; 

    cvtColor(src, edges, COLOR_BGR2GRAY); //Convert to gray 
    GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5); 
    Canny(edges, edges, 0, 50, 3); 
    dilate(edges,edges,Mat(),Point(-1,-1),3); 
    erode(edges,edges,Mat(),Point(-1,-1),3); 

    vector<vector<cv::Point> > contours; // Vector for storing contour 

    findContours(edges, contours,CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image 

    for(int i = 0; i< contours.size(); i++) // iterate through each contour. 
    { 
     double a=contourArea(contours[i],false); // Find the area of contour 
     if(a>largest_area) 
     { 
      largest_area=a; 
      largest_contour_index=i;    //Store the index of largest contour 
      bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour 
     } 
    } 

    // ------------ 
    // makes border 
    bounding_rect.x -= 10; 
    bounding_rect.y -= 10; 
    bounding_rect.width += 20; 
    bounding_rect.height += 20; 
    bounding_rect = Rect(0,0,src.cols,src.rows) & bounding_rect; 
    // ------------ 

    Mat biggest_contour_rect = src(bounding_rect).clone(); 
    imshow("biggest_contour_rect", biggest_contour_rect); 
    waitKey(0); 
    return 0; 
}