gpt4 book ai didi

python - 如何在具有最小、平均和最大面积值的 numpy 一维数组中选择子数组?

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

 def distancesplit(self):
img = np.asarray(Image.open("testtwo.tif").convert('L'))
img = 1 * (img < 127)

areasplit = np.split(img.ravel(), 24) # here we are splitting converted to 1D array
for i in areasplit:
area = (i == 0).sum()
print area

如何选择具有最小、平均和最大面积值的areasplit子数组?

最佳答案

对于最大值:

areasplit[argmax(sum(areasplit==0, axis=0)), :]

argmax 替换为 argmin 以获得最小值:您是否考虑过可能有多个数组满足您的条件?

例子:

>>> from numpy import *
>>> a=array(range(81))
>>> b=split(a, 9)
>>> b#be careful it is a list of arrays not just an array
[array([0, 1, 2, 3, 4, 5, 6, 7, 8]), array([ 9, 10, 11, 12, 13, 14, 15, 16, 17]), \
array([18, 19, 20, 21, 22, 23, 24, 25, 26]), array([27, 28, 29, 30, 31, 32, 33, 34, 35]), \
array([36, 37, 38, 39, 40, 41, 42, 43, 44]), array([45, 46, 47, 48, 49, 50, 51, 52, 53]), \
array([54, 55, 56, 57, 58, 59, 60, 61, 62]), array([63, 64, 65, 66, 67, 68, 69, 70, 71]), \
array([72, 73, 74, 75, 76, 77, 78, 79, 80])]
>>> b=array(split(a, 9)) #I prefer to use b.reshape((-1,9)) over split()., which returns an array.
>>> b#now it is an array
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])
>>> b[argmax(sum(b, axis=1)), :]
array([72, 73, 74, 75, 76, 77, 78, 79, 80])
>>> b[argmin(sum(b, axis=1)), :]
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> b[argwhere(median(b)==median(b, axis=1)).flatten(),:] #be careful there may be several matching sub-arrays
array([[36, 37, 38, 39, 40, 41, 42, 43, 44]])
>>> b[argwhere(mean(b)==mean(b, axis=1)).flatten(),:]
array([[36, 37, 38, 39, 40, 41, 42, 43, 44]])

关于python - 如何在具有最小、平均和最大面积值的 numpy 一维数组中选择子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18336001/

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