关于理论知识参考他人博客http://blog.youkuaiyun.com/zouxy09/article/details/7929531
计算图像的每一小块的LBP直方图特征如下代码所示,下面代码提取出的特征向量为8维,如果要修改维数,修改下面标注的地方。如果要取得图像LBP特征的128维时,则可分为4*4小块,对每一小块做下面操作即可,然后将每个小块的直方图联合成一个8×16的128维的向量即可。
void LBP (IplImage *src,float* lbpHist)
{
IplImage* lbpImg = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U,1);
int tmp[8]={0};
CvScalar s;
IplImage * temp = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U,1);
uchar *data=(uchar*)src->imageData;
int step=src->widthStep;
//cout<<"step"<<step<<endl;
for (int i=1;i<src->height-1;i++)
for(int j=1;j<src->width-1;j++)
{
int sum=0;
if(data[(i-1)*step+j-1]>data[i*step+j])
tmp[0]=1;
else
tmp[0]=0;
if(data[i*step+(j-1)]>data[i*step+j])
tmp[1]=1;
else
tmp[1]=0;
if(data[(i+1)*step+(j-1)]>data[i*step+j])
tmp[2]=1;
else
tmp[2]=0;
if (data[(i+1)*step+j]>data[i*step+j])
tmp[3]=1;
else
tmp[3]=0;
if (data[(i+1)*step+(j+1)]>data[i*step+j])
tmp[4]=1;
else
tmp[4]=0;
if(data[i*step+(j+1)]>data[i*step+j])
tmp[5]=1;
else
tmp[5]=0;
if(data[(i-1)*step+(j+1)]>data[i*step+j])
tmp[6]=1;
else
tmp[6]=0;
if(data[(i-1)*step+j]>data[i*step+j])
tmp[7]=1;
else
tmp[7]=0;
//计算LBP编码
s.val[0]=(tmp[0]*1+tmp[1]*2+tmp[2]*4+tmp[3]*8+tmp[4]*16+tmp[5]*32+tmp[6]*64+tmp[7]*128);
cvSet2D(lbpImg,i,j,s);//写入LBP图像
}
int lbp_bins = 8; ///////////可以修改
float lbp_ranges[] = { 0, 255 };
float* pb_ranges = lbp_ranges;
CvHistogram* hist_lbp = cvCreateHist( 1, &lbp_bins, CV_HIST_ARRAY, &pb_ranges, 1 );//生成直方图
cvCalcHist( &lbpImg, hist_lbp, 0, 0 );
cvNormalizeHist(hist_lbp,1.0);
float max=0;
cvGetMinMaxHistValue(hist_lbp,NULL,&max,NULL,NULL);
IplImage* lbpHistImg=cvCreateImage(cvSize(400,300),8,3);
cvSet(lbpHistImg,cvScalarAll(255),0);
////////////////画灰度直方图
double bin_width=(double)lbpHistImg->width/lbp_bins;
double bin_unith=(double)lbpHistImg->height/max;
for(int i=0;i<lbp_bins;i++){
CvPoint p0=cvPoint(i*bin_width,lbpHistImg->height);
CvPoint p1=cvPoint((i+1)*bin_width,lbpHistImg->height-cvGetReal1D(hist_lbp->bins,i)*bin_unith);
cvRectangle(lbpHistImg,p0,p1,cvScalar(0,255),-1,8,0);
}
for(int i=0;i<lbp_bins;i++){
lbpHist[i] = (float)cvGetReal1D(hist_lbp->bins, i);
}
cvShowImage("LBP Image",lbpImg);
cvShowImage("LBP hist",lbpHistImg);
cvWaitKey(0);
cvReleaseImage(&temp);
cvReleaseHist(&hist_lbp);
cvReleaseImage(&lbpHistImg);
cvReleaseImage(&lbpImg);
}