meanshift_segmentation.cpp 2.08 KB
Newer Older
1
#include "opencv2/highgui/highgui.hpp"
2 3
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
4

5 6 7 8 9
#include <iostream>

using namespace cv;
using namespace std;

10
static void help(char** argv)
Gary Bradski's avatar
Gary Bradski committed
11
{
12
    cout << "\nDemonstrate mean-shift based color segmentation in spatial pyramid.\n"
Gary Bradski's avatar
Gary Bradski committed
13 14 15 16 17 18 19
    << "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
20
static void floodFillPostprocess( Mat& img, const Scalar& colorDiff=Scalar::all(1) )
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
{
    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;

42
static void meanShiftSegmentation( int, void* )
43 44 45 46 47 48 49 50 51 52 53 54 55
{
    cout << "spatialRad=" << spatialRad << "; "
         << "colorRad=" << colorRad << "; "
         << "maxPyrLevel=" << maxPyrLevel << endl;
    pyrMeanShiftFiltering( img, res, spatialRad, colorRad, maxPyrLevel );
    floodFillPostprocess( res, Scalar::all(2) );
    imshow( winName, res );
}

int main(int argc, char** argv)
{
    if( argc !=2 )
    {
56
        help(argv);
57 58 59 60 61 62 63 64 65 66 67
        return -1;
    }

    img = imread( argv[1] );
    if( img.empty() )
        return -1;

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

68
    namedWindow( winName, WINDOW_AUTOSIZE );
69 70 71 72 73 74 75 76 77

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

    meanShiftSegmentation(0, 0);
    waitKey();
    return 0;
}