www.pudn.com > crackDection.zip > K-means.cpp, change:2013-07-30,size:1690b


#include "opencv2/opencv.hpp" 
 
void  k_means(IplImage* plate_image) 
{ 
	CvMat* points = cvCreateMat(plate_image->height*plate_image->width , 1 , CV_32FC1); 
	CvMat* clusters= cvCreateMat(plate_image->height*plate_image->width , 1 , CV_32SC1); 
 
	float cluster_0_count=0,cluster_1_count=0; 
	float sum_cluster_0 =0 , sum_cluster_1 = 0; 
 
	int y,x,width_step; 
	uchar* image_data; 
 
 
	image_data = (uchar*)plate_image->imageData; 
	width_step = plate_image->widthStep; 
 
	for(y=0;y<plate_image->height;y++) 
	{ 
		for(x=0;x<plate_image->width;x++) 
		{ 
			points->data.fl[y*plate_image->width+x] = (float)(*(image_data + y*width_step + x)); 
		} 
	} 
 
	cvKMeans2(points,2,clusters ,cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,10,1.0)); 
 
 
 
	for(y=0;y<plate_image->height;y++) 
	{ 
		for(x=0;x<plate_image->width;x++) 
		{ 
			int cluster_id = clusters->data.i[y*plate_image->width+x]; 
 
			if(cluster_id == 0) 
			{ 
				sum_cluster_0 = sum_cluster_0 + (float)(*(image_data + y*width_step + x)); 
				cluster_0_count  = cluster_0_count + 1; 
 
				*(image_data + y*width_step + x) = 0; 
 
			} 
			else if(cluster_id == 1) 
			{ 
				sum_cluster_1 = sum_cluster_1 + (float)(*(image_data + y*width_step + x)); 
 
				*(image_data + y*width_step + x) = 255; 
			} 
			else 
			{ 
			} 
		} 
	} 
 
 
	//平均值比较大 的  是字符  
	cluster_1_count = plate_image->height*plate_image->width - cluster_0_count; 
 
	sum_cluster_0 = sum_cluster_0 / cluster_0_count; 
	sum_cluster_1 = sum_cluster_1 / cluster_1_count; 
 
 
	if(sum_cluster_0 > sum_cluster_1) 
	{ 
		//将图像按位取反 
		cvNot(plate_image , plate_image); 
	} 
 
	cvReleaseMat(&points); 
	cvReleaseMat(&clusters); 
 
 
 
}