Home > Mobile >  What is the most efficient way to compute the sum of all pixels inside a given rectangle in an image
What is the most efficient way to compute the sum of all pixels inside a given rectangle in an image

Time:12-20

My solution is as follows:

import cv2
import numpy as np

def sum_all_pixels(image, x1, y1, x2, y2, c1=0, c2=3):
    '''
    INPUTS: the image, the coordinates of the rectangle, and the channels
    OUTPUT: sum of all pixels of the image within the rectangle
    
    image: the path to the image
    x1, y1: the coordinates of the top-left point of the rectangle
    x2, y2: the coordinates of the bottom-right point of the rectangle
    c1, c2: the range of the RGB color channels. By default, it assumed the sum is to be calculated across all 3 color channels 
    '''
    img = cv2.imread(image)
    return np.sum(img[y1:y2, x1:x2, c1:c2])

Is there any better, more efficient, algorithm to do this?

CodePudding user response:

If you can preprocess your images, you could store the integral images(summed-area table) first:

img = cv2.imread(image)
int_img = cv2.integral(img)
int_img = int_img[1:,1:]
cv2.imwrite(filename, int_img)

Then for calculating the sum:

int_img = cv2.imread(filename)
sum = int_img[y2, x2] - int_img[y1, x2] - int_img[y2, x1]   int_img[y1, x2]

CodePudding user response:

Since images in openCV are numpy arrays, you're pretty much doing this as fast as is possible.

If you're using a normal list, using the sum function in Python would be faster.

  • Related