# 【图像处理】快速计算积分图

(1+2+...+W-1)*H+(1+2+...+W)*(H=1) = (w-2)*H/(W-1)+2(W+1)*(H-1)/W

## 一种简单的快速计算方法

(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
outputMatrix[offset+j] = outputMatrix[offset+j-1] + outputMatrix[offset-width] + outputMatrix[offset-width-1] + inputMatrix[offset];
}
}
return ;
}

## 改进的快速计算方法

(W-1)+(H-1)+2*(W-1)*(H-1)

void fastIntegral(unsigned char* inputMatrix, unsigned long* outputMatrix, int width, int height){
unsigned long *columnSum = new unsigned long[width]; // sum of each column
// calculate integral of the first line
for(int i=0;i<width;i++){
columnSum[i]=inputMatrix[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
columnSum[0] +=inputMatrix[offset];
outputMatrix[offset] = columnSum[0];
// other columns
for(int j=1;j<width;j++){
columnSum[j] += inputMatrix[offset+j];
outputMatrix[offset+j] = outputMatrix[offset+j-1] + columnSum[j];
}
}
return ;
}