图像分析:积分图像与代码实现

时间:2023-02-07 09:45:50

积分图像(Integral Image)的概念是由Viola和Jones在文献[1]中提出的。

积分图像中任意一点(i,j)的值ii(i,j)为原图像左上角到任意点(i,j)相应对角线区域灰度值总和。可以用如下两式迭代计算得到

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

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

求积分图像只需对原图像所有像素进行一遍扫描。

用C++编程实现如下:(pOutImage为输出的积分图,pInImage为输入的灰度图)


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;

img=double(imread('lena.jpg'));
[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.

[2] http://www.cnblogs.com/tiandsp/archive/2013/04/12/3016402.html