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的值,以便觀察不同參數下的效果。截圖例如以下
以下圖是源圖片