算法介绍见:图像分割—基于图的图像分割(Graph-Based Image Segmentation)
原文是Linux平台,图像格式PPM,比较不习惯,我改成了OpenCV,效果有一点点差别,应该是高斯滤波效果有差异。
此外,原算对边排序时,直接比较结构体,std::sort(edges, edges + num_edges); 按理说只比较边才对啊,于是我又改了std::sort(edges, edges + num_edges, [](const edge &e1, const edge &e2) {return e1.w < e2.w; });……效果会有很大差异!原因,下次再说
我加的注释是语句的右边//开头的部分,不好意思是用英文写的,原因在于我写的能力太差,权当练习,如有错误,纯属正常
main.cpp
#include <vector>
#include <ctime>
#include "opencv2/opencv.hpp"
#include "segmentimage.h"
using namespace std;
using namespace cv;
// Computer Vision A Reference Guide
int main()
{
//const char* imagename = "G:\\Pic\\101087_big.jpg";
const char* imagename = "G:/Pic/beach.png";
//const char* imagename = "grain.bmp";
//const char* imagename = "person_272.png";
//从文件中读入图像
Mat img = imread(imagename);
//如果读入图像失败
if (img.empty())
{
fprintf(stderr, "Can not load image %s\n", imagename);
return -1;
}
//显示图像
imshow("image", img);
//cvtColor(img, img, CV_BGR2Lab);// May be using lab color space will be better
Mat gray;
cvtColor(img, gray, CV_BGR2GRAY);
img.convertTo(img,CV_32FC3);
float sigma = 0.5;
float k = 500;
int min_size = 100;
int num_ccs;
clock_t tt = clock();
Mat result = segment_image(img, sigma, k, min_size, &num_ccs);
tt = clock() - tt;
float process_time = (float)tt / CLOCKS_PER_SEC;
cout << "get " << num_ccs << " components" << endl;
cout << "process time: " << process_time<<endl;
imshow("process result", result);
cvtColor(gray, gray, CV_GRAY2BGR);
imshow("overlay result", gray*0.25 + result*0.75);
//此函数等待按键,按键盘任意键就返回
waitKey();
return 0;
}
segment_image.cpp
/*
Copyright (C) 2006 Pedro Felzenszwalb
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <cstdlib>
//#include "filter.h"
#include "segmentgraph.h"
#include "segmentimage.h"
#include "time.h"
// random color
rgb random_rgb(){
rgb c;
double r;
srand(unsigned(time(NULL)));
c.r = rand()%25