计算图像中给定矩形内所有像素之和的最有效方法是什么



我的解决方案如下:

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])

有没有更好、更高效的算法可以做到这一点?

如果你可以预处理你的图像,你可以先存储积分图像(面积总和表(:

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

然后计算总和:

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

由于openCV中的图像是numpy数组,因此您几乎可以尽可能快地执行此操作。

如果您使用的是普通列表,那么在Python中使用sum函数会更快。

最新更新