opencv中的meanshift图像切割

时间:2022-04-06 08:44:08

Meanshift(均值漂移)是一种在一组数据的密度分布中寻找局部极值的稳定的方法。Meanshift不仅能够用于图像滤波,视频跟踪,还能够用于图像切割。

通过给出一组多维数据点,其维数是(x,y,r,g,b),均值漂移能够用一个窗体扫描空间来找到数据密度最大的区域,能够理解为数据分布最集中的区域。

在这里须要注意,因为空间位置(也就是上面的x和y)的变化范围与颜色的变化范围(上面的r,g,b)有极大的不同,所以,meanshift对这两个维数要採用不同的窗体半径。在opencv自带的meanshift切割函数cvPyrMeanShiftFiltering()中,就专门有2个半径參数,各自是spatialRadius和colorRadius,这两个參数分别代表的是空间半径(x,y)和颜色(r,g,b)半径。

当均值漂移窗体移动时,经过窗体变换后收敛到数据峰值的全部点都会连通起来,而且属于该峰值。这样的所属关系从密集的尖峰辐射,形成了图像的切割。opencv中的meanshift切割实际上是由比例金字塔(cvPyrUP(),cvPyrDown())完毕的,相关的介绍大家能够看年learning
opencv中关于图像金字塔的介绍。

以下的代码是我自己写的,大家能够參考一下。PS:我执行的时候发现实际上cvPyrMeanShiftFiltering的执行效率并非非常高,特别是把spatialRadius的值增大以后迭代时感觉非常费时。

#include"highgui.h"
#include"cv.h" #include <iostream> using namespace cv;
using namespace std; IplImage* src; //source image
IplImage* dst; //the dst image after meanshift
int spatialRad=10,colorRad=20,maxPryLevel=1; void on_Meanshift(int ) //the callback function
{ //cout<<"spatialRad="<<spatialRad<<endl; //for test
//cout<<" colorRad="<<colorRad<<endl;
//cout<<" maxPryLevel="<<maxPryLevel<<endl;
cvPyrMeanShiftFiltering(src,dst,spatialRad,colorRad,maxPryLevel); //segmentation use meanshift
cvShowImage("dst",dst); //show the segmented image }
void main()
{
src = cvLoadImage("1.png"); //load the picture
CvSize size;
size.width = src->width;
size.height = src->height;
dst = cvCreateImage(size,src->depth,3); //set the size of the dst image
cvNamedWindow("src",CV_WINDOW_AUTOSIZE);
cvNamedWindow("dst",CV_WINDOW_AUTOSIZE);
cvShowImage("src",src);
cvPyrMeanShiftFiltering(src,dst,spatialRad,colorRad,maxPryLevel); //create the trackbar
cvCreateTrackbar("spatialRad","dst",&spatialRad,50,on_Meanshift);
cvCreateTrackbar("colorRad","dst",&colorRad,60,on_Meanshift);
cvCreateTrackbar("maxPryLevel","dst",&maxPryLevel,5,on_Meanshift); cvShowImage("dst",dst); cvWaitKey(0);
}

在代码中使用了trackbar,因此能够自己 改变spatialRad,colorRad,maxPryLevel的值,以便观察不同參数下的效果。截图例如以下

opencv中的meanshift图像切割

以下图是源图片

opencv中的meanshift图像切割