# 图像分析：积分图像与代码实现

s(i,j)=s(i,j-1)+i(i,j)

ii(i,j)=ii(i-1,j)+s(i,j)

pOutImage[0][0]=pInImage[0][0];
for (int x=1;x<nWidth;x++)
{
pOutImage[x][0]=pInImage[x-1][0]+pInImage[x][0];
}
for(int y=1;y<nHeight;y++)
{
int nSum=0；
for(int x=0;x<nWidth;x++)
{
nSum+=pInImage[x][y];
pOutImage[x][y]=pInImage[x][y-1]+nSum;
}
}

OpenCV中的编程实现：

/*
* icvGetAuxImages
*
* Get sum, tilted, sqsum images and calculate normalization factor
* All images must be allocated.
*/
static
void icvGetAuxImages( CvMat* img, CvMat* sum, CvMat* tilted,
CvMat* sqsum, float* normfactor )
{
CvRect normrect;
int p0, p1, p2, p3;
sum_type   valsum   = 0;
sqsum_type valsqsum = 0;
double area = 0.0;

cvIntegral( img, sum, sqsum, tilted );
normrect = cvRect( 1, 1, img->cols - 2, img->rows - 2 );
CV_SUM_OFFSETS( p0, p1, p2, p3, normrect, img->cols + 1 )

area = normrect.width * normrect.height;
valsum = ((sum_type*) (sum->data.ptr))[p0] - ((sum_type*) (sum->data.ptr))[p1]
- ((sum_type*) (sum->data.ptr))[p2] + ((sum_type*) (sum->data.ptr))[p3];
valsqsum = ((sqsum_type*) (sqsum->data.ptr))[p0]
- ((sqsum_type*) (sqsum->data.ptr))[p1]
- ((sqsum_type*) (sqsum->data.ptr))[p2]
+ ((sqsum_type*) (sqsum->data.ptr))[p3];

/* sqrt( valsqsum / area - ( valsum / are )^2 ) * area */
(*normfactor) = (float) sqrt( (double) (area * valsqsum - (double)valsum * valsum) );
}


Matlab实现代码如下：

clear all;
close all;
clc;

[m n]=size(img);

%计算积分图
I=zeros(m,n);
for i=1:m
for j=1:n
if i==1 && j==1             %积分图像左上角
I(i,j)=img(i,j);
elseif i==1 && j~=1         %积分图像第一行
I(i,j)=I(i,j-1)+img(i,j);
elseif i~=1 && j==1         %积分图像第一列
I(i,j)=I(i-1,j)+img(i,j);
else                        %积分图像其它像素
I(i,j)=img(i,j)+I(i-1,j)+I(i,j-1)-I(i-1,j-1);
end
end
end


reference：

[1] Viola P, Jones M. Rapid object detection using a boosted cascade of simple features[C]//Computer Vision and Pattern Recognition, 2001. CVPR 2001. Proceedings of the 2001 IEEE Computer Society Conference on. IEEE, 2001, 1: I-511-I-518 vol. 1.