weilin_1216

导航

opencv图像分割

本次试验基于opencv2.4.5版本中自带的一个sample。其主要过程是,首先设置好参数,然后用函数pyrMeanShiftFiltering()对输入的图像进行分割。分割后的结果保存在该函数的第二个参数即输出图像中,最后根据该分割图像的特点用floodFill()函数对其分割的结果用不同的颜色进行填充。

实现代码如下:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace cv;
using namespace std;

/*static void help(char** argv)
{
    cout << "\nDemonstrate mean-shift based color segmentation in spatial pyramid.\n"
    << "Call:\n   " << argv[0] << " image\n"
    << "This program allows you to set the spatial and color radius\n"
    << "of the mean shift window as well as the number of pyramid reduction levels explored\n"
    << endl;
}*/

//This colors the segmentations
static void floodFillPostprocess( Mat& img, const Scalar& colorDiff=Scalar::all(1) )
{
    CV_Assert( !img.empty() );
    RNG rng = theRNG();
    Mat mask( img.rows+2, img.cols+2, CV_8UC1, Scalar::all(0) );
    for( int y = 0; y < img.rows; y++ )
    {
        for( int x = 0; x < img.cols; x++ )
        {
            if( mask.at<uchar>(y+1, x+1) == 0 )
            {
                Scalar newVal( rng(256), rng(256), rng(256) );
               floodFill( img, mask, Point(x,y), newVal, 0, colorDiff, colorDiff );

            }
        }
    }
}

string winName = "meanshift";
int spatialRad, colorRad, maxPyrLevel;
Mat img, res;

static void meanShiftSegmentation( int, void* )
{
    cout << "spatialRad=" << spatialRad << "; "
         << "colorRad=" << colorRad << "; "
         << "maxPyrLevel=" << maxPyrLevel << endl;
         //调用meanshift图像金字塔进行分割
    pyrMeanShiftFiltering( img, res, spatialRad, colorRad, maxPyrLevel );
    floodFillPostprocess( res, Scalar::all(2) );
    imshow( "res", res );
}

int main(int argc, char** argv)
{
    /*if( argc !=2 )
    {
        help(argv);
        return -1;
    }*/

    img = imread("stuff.jpg");
    if( img.empty() )
        return -1;

    spatialRad = 10;
    colorRad = 20;
    maxPyrLevel = 1;

    namedWindow( "img", CV_WINDOW_AUTOSIZE );
    namedWindow( "res", CV_WINDOW_AUTOSIZE );

    createTrackbar( "spatialRad", "res", &spatialRad, 80, meanShiftSegmentation );
    createTrackbar( "colorRad", "res", &colorRad, 60, meanShiftSegmentation );
    createTrackbar( "maxPyrLevel", "res", &maxPyrLevel, 5, meanShiftSegmentation );

    meanShiftSegmentation(0, 0);
    imshow("img",img);
    imshow("res",img);

    waitKey();
    return 0;
}

 

参考链接:http://www.cnblogs.com/tornadomeet/archive/2012/06/06/2538695.html

posted on 2013-07-03 10:30  weilin_1216  阅读(891)  评论(0编辑  收藏  举报