简体   繁体   English

使用Opencv调整大小/裁剪图像

[英]Resizing/Cropping an image using Opencv

I'm new to OpenCV and was hoping to get help on a project I'm working on. 我是OpenCV的新手,希望在我正在从事的项目中获得帮助。 I want to separate the foreground from the background and resizing / cropping the original image so that the foreground fits. 我想将前景与背景分开,并调整大小/裁剪原始图像,以适合前景。

I have this sample, and i would like to be able to get an optimal result like this: 我有这个样本,我希望能够获得这样的最佳结果:

Before 之前
在此处输入图片说明

After
在此处输入图片说明

a simple code just to give an idea. 一个简单的代码只是为了给出一个想法。 it works fine for images like yours. 它适用于像您这样的图像。

(note: i used this code partly) (注意:我部分使用了此代码

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM