본문 바로가기

Others/Odds & Ends

적분 영상(integral image)의 쉬운 구현

#define IMAGE_WIDTH   4
#define IMAGE_HEIGHT  6
#define IMAGE_SIZE   (IMAGE_WIDTH*IMAGE_HEIGHT)
#define INTEGRAL_IMAGE_SIZE ((IMAGE_WIDTH+1)*(IMAGE_HEIGHT+1))
void MakeIntegralImage(float *image, float *integralImage, int width, int height)
{
 register int x, y;
 integralImage[0] = image[0];
 for(x=1; x<width; ++x)
 {
  integralImage[x] = integralImage[x-1] + image[x];
 }
 float linesum = 0.0f;
 for(y=1; y<height; ++y) 
 {
  linesum = 0.0f;
  for(x=0; x<width; ++x) 
  {
   linesum += image[y*width+x];
   integralImage[y*width+x] = integralImage[(y-1)*width+x] + linesum;
  }
 }
} 

int _tmain(int argc, _TCHAR* argv[])
{
 float IMAGE[IMAGE_SIZE] = {10, 10, 10, 10, 
          20, 20, 20, 20,
          30, 30, 30, 30,
          40, 40, 40, 40, 
          30, 30, 30, 30,
          20, 20, 20, 20,
         };
 float INTEGRAL_IMAGE[IMAGE_SIZE] = {0, };
 MakeIntegralImage(IMAGE, INTEGRAL_IMAGE, IMAGE_WIDTH, IMAGE_HEIGHT);
 float rectSum1 = 30+30+40+40+30+30;
 float integralSum1 = 390-90-130+30;

 float rectSum2 = 10+10+20+20+30+30+40+40+30+30+20+20;
 float integralSum2 = 300-0-0+0;
 
 /*
 //Result 
 INTEGRAL_IMAGE[IMAGE_SIZE] = {10,  20,  30,  40,
          30,  60,  90,  120,
          60,  120, 80,  240,
          100, 200, 300, 400,
          130, 260, 390, 520,
          150, 300, 450, 600,} 
 */
 /*
 //실제로는 아래와 같이 값이 생긴다고 여길 수 있음.  
 INTEGRAL_IMAGE[INTEGRAL_IMAGE_SIZE] = {0, 0,   0,   0,   0,
             0, 10,  20,  30,  40,
             0, 30,  60,  90,  120,
             0, 60,  120, 80,  240,
             0, 100, 200, 300, 400,
             0, 130, 260, 390, 520,
             0, 150, 300, 450, 600,} 
 */
 float sum = 0;
 for(int i=0; i<IMAGE_SIZE; i++)
 {
  sum += IMAGE[i];
 }
 printf("sum: %f\n", sum);
 return 0;
}