计算图像中给定矩形内所有像素总和的最有效方法是啥?

Posted

技术标签:

【中文标题】计算图像中给定矩形内所有像素总和的最有效方法是啥?【英文标题】:What is the most efficient way to compute the sum of all pixels inside a given rectangle in an image?计算图像中给定矩形内所有像素总和的最有效方法是什么? 【发布时间】:2022-01-21 18:43:28 【问题描述】:

我的解决方法如下:

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

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

【问题讨论】:

如果单个图像有很多矩形,则应使用整体图像预处理。之后,每个矩形只需读取 4 个值即可计算所需的总和。 【参考方案1】:

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

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

【讨论】:

【参考方案2】:

如果你可以预处理你的图像,你可以先存储完整的图像(summed-area table):

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]

【讨论】:

以上是关于计算图像中给定矩形内所有像素总和的最有效方法是啥?的主要内容,如果未能解决你的问题,请参考以下文章

Python3:计算两个列表的所有排列总和为 100 的最有效方法是啥?

计算径向轮廓的最有效方法

检测图像中矩形的最简单*正确*方法是啥?

使用 Ruby,获取给定 URL 的内容类型的最有效方法是啥?

计算具有给定总和的子集的有效方法

计算熊猫中出现次数的最有效方法是啥?