积分图是图像中十分常用的方法,最初是在计算Haar特征值时的快速计算方法,后来在均值滤波,二值化等图像处理方法中也十分常见。积分图的计算原理:
C++代码(亲测通过):
/******************************************
* 快速计算积分图
* Integral(i,j) = Integral(i,j-1) + Integral(i-1,j) - Integral(i-1,j-1) + Image(i,j)
* 于是,对一张W*H的图像直接求取积分图,需要:(W-1)+(H-1)+3*(W-1)*(H-1)次加法
*/
void Integral(unsigned char* inputMatrix, unsigned long* outputMatrix, int width, int height)
{
// calculate integral of the first line
for(int i=0;i<width;i++){
outputMatrix[i] = inputMatrix[i];
if(i>0){
outputMatrix[i] += outputMatrix[i-1];
}
}
for (int i=1;i<height;i++){
int offset = i*width;
// first column of each line
outputMatrix[offset] = outputMatrix[offset-width] + inputMatrix[offset];
// other columns
for (int j = 1; j < width; j++) {
outputMatrix[offset+j] = outputMatrix[offset + j - 1] +
outputMatrix[offset + j - width] -
outputMatrix[offset + j - width - 1] +
inputMatrix[offset + j];
}
}
return;
}
// test
int main(int argc, char** argv)
{
cout << ">> ----" << "\n" << endl;
int nRows = 4;
int nCols = 6;
unsigned char inputMatrix[24] = {1,2,3,4,5,6,
1,1,1,1,1,1,
2,1,2,1,2,1,
4,5,6,1,2,3};
unsigned long outputMatrix[24];
memset(outputMatrix, 0, 24*sizeof(unsigned long));
Integral(inputMatrix, outputMatrix, nCols, nRows);
for(int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
cout << setw(5) << outputMatrix[r * nCols + c];
}
cout << endl;
}
cout << "\n" << ">> ----" << endl;
return 0;
}