图像分割—基于图的图像分割(OpenCV源码注解)

这篇博客介绍了如何使用OpenCV实现基于图的图像分割,并对比了原始算法在Linux环境下处理PPM图像与OpenCV实现的差异。作者修改了原算法中边的排序方式,以结构体权重进行比较,导致了效果变化。博客提供了相关源码文件供读者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法介绍见:图像分割—基于图的图像分割(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
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值