在网上没有找到这个函数的调用,故自己写了一点。
在OpenCV 2.3中 meanshift定义为
CVAPI(int) cvMeanShift( const CvArr* prob_image, CvRect window,
CvTermCriteria criteria, CvConnectedComp* comp );
其中第一个参数const CvArr* prob_image为输入图像,我用是IplImage* 类型的,注意必须是单通道的;
第二个参数CvRect window是开始的窗口,需要指定一下;
第三个参数CvTermCriteria criteria是说明迭代到多少次算完,这里参考网上别人给的,设置为TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 1000, 0.1) ,其中那个1000指迭代次数,0.1指的是迭代条件,没有仔细研究到底指什么小于0.1,因为之后自己就没有再使用meanshift做东西,具体TermCriteria的参数设置可以参考:
Termination criteria for iterative algorithms.
;
- int type
type of the termination criteria, one of:
- CV_TERMCRIT_ITER - stop the algorithm after max_iter iterations at maximum.
- CV_TERMCRIT_EPS - stop the algorithm after the achieved algorithm-dependent accuracy becomes lower than epsilon.
- CV_TERMCRIT_ITER+CV_TERMCRIT_EPS - stop the algorithm after max_iter iterations or when the achieved accuracy is lower than epsilon, whichever comes the earliest.
- int max_iter
Maximum number of iterations
- double epsilon
Required accuracy
第四个参数CvConnectedComp* comp是返回值,里面存储结果,其中comp->rect是收敛后窗口位置,comp->area是最终窗口中所有像素点的和。
调用过程如下:
#include <stdlib.h>
#include <stdio.h>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <math.h>
using namespace std;
using namespace cv;
void main()
{
char image_name[100];//存储打开文件名称
uchar* m_b = NULL;
IplImage* img = 0;
CvConnectedComp my_mp;
int win_width = 50;//初始搜索窗口
sprintf(image_name, "%s%s", "D:\\mean", ".bmp");
img = cvLoadImage(image_name);//打开图片
IplImage* img_shift = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 1);
IplImage* pic = cvCreateImage(cvSize(img->width,img->height), IPL_DEPTH_8U, 3);
cvCvtColor(img, img_shift, CV_BGR2GRAY);//必须是单通道图片才可以
cvNamedWindow( "mainWin");//创建窗口
cvMeanShift(img_shift, cvRect(0,0,win_width,win_width), //这里的初始窗口需要重新设置一下
TermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 1000, 0.1), &my_mp);
CV_IMAGE_ELEM(img_shift, uchar, my_mp.rect.y+win_width/2, my_mp.rect.x+win_width/2) = 255;//把最后的收敛窗口标出来
printf("Draw the point is done!\n");
cvCvtColor(img_shift, pic, CV_GRAY2BGR);
cvSaveImage("D:\\after_mean.bmp", pic);
cvShowImage("mainWin", img_shift);
cvWaitKey(0);
cvDestroyWindow("mainWin");
cvReleaseImage(&img);
cvReleaseImage(&img_shift);
cvReleaseImage(&pic);
}