OpenCVベースLBPアルゴリズム(OpenCV 1.0バージョン)


#include 
#include 
#include 

using namespace std;
using namespace cv;
//      opencv LBP  opencv1.0  
// 3 x 3       
// [ 1, 2, 3]
// [ 8, ij,4]
// [ 7, 6, 5]
void LBP(IplImage *src, IplImage *dst)
{
	//               
	assert(src != NULL && src->nChannels == 1);

	int tmp[8] = { 0 };

	int rows = src->height - 1;
	int cols = src->width - 1;
	
	for (int i = 1; i < rows; ++i)
	{
		for (int j = 1; j < cols; ++j)
		{
			int sum = 0;
			double val = cvGetReal2D(src, i, j);
			double tempVal = 0.0;

			tempVal = cvGetReal2D(src, i - 1, j - 1);		//    
			tempVal > val ? tmp[0] = 255 : tmp[0] = 0;
			tempVal = cvGetReal2D(src, i, j - 1);			//    
			tempVal > val ? tmp[1] = 255 : tmp[1] = 0;
			tempVal = cvGetReal2D(src, i + 1, j - 1);		//    
			tempVal > val ? tmp[2] = 255 : tmp[2] = 0;
			tempVal = cvGetReal2D(src, i + 1, j);			//   
			tempVal > val ? tmp[3] = 255 : tmp[3] = 0;		
			tempVal = cvGetReal2D(src, i + 1, j + 1);		//    
			tempVal > val ? tmp[4] = 255 : tmp[4] = 0;
			tempVal = cvGetReal2D(src, i, j + 1);			//    
			tempVal > val ? tmp[5] = 255 : tmp[5] = 0;
			tempVal = cvGetReal2D(src, i - 1, j + 1);		//    
			tempVal > val ? tmp[6] = 255 : tmp[6] = 0;		
			tempVal = cvGetReal2D(src, i - 1, j);			//   
			tempVal > val ? tmp[7] = 255 : tmp[7] = 0;

			//    LBP   
			for (int k = 0; k < 8; ++k)
			{
				sum += tmp[k] * pow(2, k);
			}

			cvSetReal2D(dst, i, j, sum);
		}
	}
}

//    LBP   
void ELBP(IplImage* src, IplImage* dst, int radius, int neighbors)
{
	//            
	assert(src->nChannels == 1);

	for (int i = 0; i < neighbors; ++i)
	{
		//     
		double sRadian = sin(2.0 * CV_PI * i / static_cast(neighbors));
		//     
		double cRadian = cos(2.0 * CV_PI * i / static_cast(neighbors));

		//       
		double x = static_cast(-radius * sRadian);
		double y = static_cast(radius * cRadian);

		//      
		int fx = static_cast(floor(x));
		int fy = static_cast(floor(y));
		//      
		int cx = static_cast(ceil(x));
		int cy = static_cast(ceil(y));
		//     
		double tx = x - fx;
		double ty = y - fy;

		//       
		double w1 = (1 - tx) * (1 - ty);
		double w2 = tx * (1 - ty);
		double w3 = (1 - tx) * ty;
		double w4 = tx * ty;

	
		//         
		for (int rows = radius; rows < src->height - radius; ++rows)
		{
			for (int cols = radius; cols < src->width - radius; ++cols)
			{
				//     
				double t1 = w1 * cvGetReal2D(src, rows + fy, cols + fx);
				double t2 = w2 * cvGetReal2D(src, rows + fy, cols + cx);
				double t3 = w3 * cvGetReal2D(src, rows + cy, cols + fx);
				double t4 = w4 * cvGetReal2D(src, rows + cy, cols + cx);
				double t = t1 + t2 + t3 + t4;

				double val = cvGetReal2D(src, rows, cols);
				double epsilon = std::numeric_limits::epsilon();

				uchar c = ((t > val) || abs(t - val) < epsilon);
				uchar tmp = c * pow(2, i);
				double v = cvGetReal2D(dst, rows - radius, cols - radius);
				v += tmp;
				cvSetReal2D(dst, rows - radius, cols - radius, v);
			}
		}

	}

}