关于meanshitf的介绍:
mean shift 图像分割 (一): 1 总体思想,2 算法步骤
mean shift 图像分割 (二): 3 算法原理,4 延伸
mean shift 图像分割 (三): 5 非参数密度估计
不得不说,这个OpenCV实现实在不咋地,
这次我改风格了,中英文杂合注释
main.cpp
#include "opencv2/opencv.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;
pyrMeanShiftFiltering(img, res, spatialRad, colorRad, maxPyrLevel);
floodFillPostprocess(res, Scalar::all(2));
imshow(winName, res);
}
int main(int argc, char** argv)
{
//if (argc != 2)
//{
// help(argv);
// return -1;
//}
string fimg = "G:/Pic/fruits.jpg";//"G:/Pic/2012060619243397.png";
img = imread(fimg);
if (img.empty())
return -1;
//640-by-480 it works well to set spatialRadiusequal = 2 and colorRadiusequal = 40
// max_level, which describes how many levels of scale pyramid you want
//used for segmentation.A max_levelof 2 or 3 works well for a 640 - by - 480 color image
spatialRad = 40;
colorRad = 22;
maxPyrLevel = 2;
namedWindow(winName, WINDOW_AUTOSIZE);
createTrackbar("spatialRad", winName, &spatialRad, 80, meanShiftSegmentation);
createTrackbar("colorRad", winName, &colorRad, 60, meanShiftSegmentation);
createTrackbar("maxPyrLevel", winName, &maxPyrLevel, 5, meanShi