GongXinyuu
1/29/2019 - 6:30 AM

integral image

integral image

import numpy as np
from imageio import imsave, imread
import matplotlib.pyplot as plt
    
img_name = 'xxx.jpg'
img = imread(img_name)

class IntegralImage(object):
    def __init__(self, img):
        assert len(np.shape(img))==2
        self.height, self.width = np.shape(img)
        self.img = img
        self.sum_table = np.array([[None] * self.width] * self.height)
        self.prepare()
    
    def cum(self, y, x):
        if x<0 or y<0:
            return 0
        elif self.sum_table[y][x] is None:
            self.sum_table[y][x] = self.cum(y-1, x) + self.cum(y, x-1) - self.cum(y-1, x-1) + self.img[y][x]
            return self.sum_table[y][x]
        else:
            return self.sum_table[y][x]
        
    def prepare(self):
        self.cum(self.height-1, self.width-1)
        
    def cal(self, x0, y0, x1, y1):
        assert x0 < x1
        assert y0 < y1
        
        summation = self.cum(y1, x1) + self.cum(y0, x0) - self.cum(y1, x0) - self.cum(y0, x1)
        #print(self.cum(y1, x1), self.cum(y0, x0), self.cum(y1, x0), self.cum(y0, x1))
        
        return summation
             
              
integral_img = IntegralImage(img.sum(2))
integral_img.cal(5,10,100,20)