Python 如何计算“的平均值”;";使用for循环并将其分配给变量后得到的输出?
我使用for循环来计算图像中diff段的一系列阈值Python 如何计算“的平均值”;";使用for循环并将其分配给变量后得到的输出?,python,numpy,multidimensional-array,mean,Python,Numpy,Multidimensional Array,Mean,我使用for循环来计算图像中diff段的一系列阈值 >>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
>>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计算这些阈值(输出值)的平均值并将其存储在变量中?您可以
修改您的代码,使其如下所示,请注意for循环的部分和for循环后的
。本质上,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()
计算出结果,但最终如果超出for循环
,您将得到这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
有很多方法可以做到这一点:
使用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)
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)
不使用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)
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)
你试过什么?你已经标记了numpy你能试着使用这个库吗?