簡體   English   中英

圖像段中所有像素的強度值之和

[英]Sum of the intensity values of all pixels in image segment

根據下面顯示的公式,我需要通過將段中的強度值之和除以段中的像素數來計算平均閾值。

公式

其中 Xi' 是二進制掩碼 ( structure_mask ),|Xi'| 是許多個( xi_modulus )。 I(x,y) 是像素強度。

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
...
...
structure_mask = np.logical_and(magnitude_mask, intensity_mask).astype(np.uint8)
xi_modulus = np.count_nonzero(structure_mask.all(axis=2))
intensity_sum  # = ??

如何用numpy計算強度總和?

編輯:根據@HansHirse 的回答,我嘗試執行以下操作:

thresh_val = np.mean(img_gray[structure_mask])

而且我有IndexError: too many indices for array

其中structure_mask的形狀為(1066, 1600,1)img_gray - (1066,1600)

更新:只是一個虛假的錯誤。 通過適當的索引修復了形狀不匹配

structure_mask = np.logical_and(magnitude_mask, intensity_mask)[:, :, 0]

使用 NumPy 的boolean 數組索引,您可以輕松訪問所需的值。 您只需要注意,您的mask (或片段)是 NumPy 的bool_類型。

讓我們看一下這個簡短的代碼片段,其中我將從np.mean獲得的平均值與由給定公式明確計算的平均值進行比較:

import cv2
import numpy as np

# Some artificial image
img = np.uint8(255 * np.tile(np.linspace(1, 0, 400), (400, 1)))
cv2.imshow('img', img)

# Some mask (or segment)
mask = np.zeros((400, 400), np.uint8)
mask[10:390, 10:30] = 255
cv2.imshow('mask', mask)

# Convert mask to bool_ type
mask = np.bool_(mask)

# Calculate mean by NumPy's mean
mean = np.mean(img[mask])
print('mean by np.mean:\n', mean)

# Calculate mean explicitly by given formula
mean = np.sum(img[mask]) / np.count_nonzero(mask)
print('mean by formula:\n', mean)

cv2.waitKey(0)
cv2.destroyAllWindows()

輸出(此處省略圖片):

mean by np.mean:
 242.05
mean by formula:
 242.05

希望有幫助!

numpy 支持邏輯索引,所以

magnitude_mask[intensity_mask].mean()

會給你你想要的。

如果您堅持使用 sum

magnitude_mask[intensity_mask].sum()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM