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[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/