如何计算使用for循环并将其赋值给变量后得到的“n”输出的平均值?

问题描述 投票:-1回答:2

我使用for循环来计算图像中不同段的一系列阈值。

>>crdf
[(11, 6),
 (11, 7),
 (11, 11),
 (12, 16),
 (10, 9),
 (21, 26),
 (15, 15),
 (12, 17),
 (12, 12),
 (14, 10),
 (20, 26)
]

>>for i in range(0,4):
>>    print(threshold_otsu(img[crdf[i]],16))

-14.606459
-15.792943
-15.547393
-16.170353

如何计算这些阈值(输出值)的平均值并使用python将其存储在变量中?

python numpy multidimensional-array mean
2个回答
0
投票

您可以modify您的代码看起来像以下,注意for loop部分和after the for loop。基本上for循环中的所有数字都被附加到一个数组并计算然后我们计算for循环后该数组中数字的平均值:

crdf = [(11, 6),
 (11, 7),
 (11, 11),
 (12, 16),
 (10, 9),
 (21, 26),
 (15, 15),
 (12, 17),
 (12, 12),
 (14, 10),
 (20, 26)
]

arrayOfNumbers=[]

for i in range(0,4):
    arrayOfNumbers.append(threshold_otsu(img[crdf[i]],16))

mean = float(sum(arrayOfNumbers)) / max(len(arrayOfNumbers), 1)
print(mean)

我不知道你是如何用threshold_otsu()计算出来的,但最终如果out of the for loop你会得到这4个值并且它们会附加到arrayOfNumbers你会遇到这样的情况:

#the array will have for example these 4 values
arrayOfNumbers=[-14.606459, -15.792943, -15.547393, -16.170353]


mean = float(sum(arrayOfNumbers)) / max(len(arrayOfNumbers), 1)
print(mean)
#-15.529287

1
投票

许多方法可以做到这一点:

使用numpy:

import numpy as np

thresholds = []
for i in range(0,4):
    thresholds.append(threshold_otsu(img[crdf[i]],16))

mean_threshold = np.mean(thresholds)

不使用numpy:

threshold_sum = 0
i_values = range(0,4)
for i in i_values:
    threshold_sum += threshold_otsu(img[crdf[i]],16)

mean_threshold = threshold_sum / len(i_values)
© www.soinside.com 2019 - 2024. All rights reserved.