gpt4 book ai didi

python - 图像片段中所有像素的强度值之和

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:31 26 4
gpt4 key购买 nike

根据下面显示的公式,我需要通过将段中的强度值之和除以段中的像素数来计算平均阈值。

formula

其中 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 array indexing ,您可以轻松访问所需的值。您只需要注意,您的掩码(或段)是 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

希望对您有所帮助!

关于python - 图像片段中所有像素的强度值之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com