Meanshift图像分割


title: Meanshift图像分割
date: 2018-10-5
categories: 图像处理
tags:
- OpenCv
- 图像处理
- c++

Meanshift图像分割

Meanshift是一种特征空间分析方法,要利用此方法来解决特定问题,需要将该问题映射到特征空间。对于图像分割,我们可以映射到颜色特征空间,比如将RGB图片,映射到LUV特征空间。图像分割就是求每一个像素点的类标号。类标号取决于它在特征空间所属的cluster。对于每一个cluster,都有一个类中心,和类中心周围的点形成了一个类,即类中心对类中的点构成一个basin of attraction。如此,图像分割问题,就可以看成对每个像素点,找它的类中心问题,类中心一样的点就是一类。

meanshift认为中心是概率密度(probalility density function )的极大值点。对于每个点进行迭代搜索找到它的类中心。这种迭代搜索的策略在最优化中称之为multiple restart gradient descent。不过,一般的gradient descent并不能保证收敛到局部极值,但meanshift 可以做到,因为它的步长是自适应调整的,越靠近极值点步长越小。

meanshift的核心:密度估计(Density Estimation) 和mode 搜索。对于图像数据,其分布无固定模式可循,所以密度估计必须用非参数估计,选用的是具有平滑效果的核密度估计(Kernel density estimation,KDE)。

计算步骤

image

代码实现


#include "opencv2/opencv.hpp"
#include <iostream>
#include"time.h"
#include <omp.h>
using namespace cv;
using namespace std;

//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));
	#pragma omp parallel for
	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);
	imwrite("meanshift.tif", res);
	img.release();
	res.release();
}


int main(int argc, char** argv)
{
	int a = clock();
	string fimg = "ER0363.tif";
	img = imread(fimg);
	if (img.empty())
		return -1;	
	spatialRad = 10;
	colorRad = 10;
	maxPyrLevel = 1;
	namedWindow(winName, WINDOW_GUI_NORMAL);	
	meanShiftSegmentation(0, 0);
	int b = clock();
	
	cout << "total time: " << (b - a)<<"ms"<<endl;
	
	waitKey();
	
	return 0;
}

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值