【问题标题】: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 个值即可计算所需的总和。

标签: python opencv computer-vision


【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2011-06-05
      • 2019-01-06
      • 2019-03-09
      相关资源
      最近更新 更多