我的解決方案如下:
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])
有沒有更好、更有效的演算法來做到這一點?
uj5u.com熱心網友回復:
如果可以預處理影像,則可以先存盤積分影像(總面積表):
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]
uj5u.com熱心網友回復:
由于 openCV 中的影像是 numpy 陣列,因此您幾乎可以盡可能快地執行此操作。
如果您使用的是普通串列,則在 Python 中使用 sum 函式會更快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393764.html
