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

标签 python opencv python-2.7 numpy scipy

 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/

相关文章:

python - 找到 map 中每个像素的最近邻居

python:遍历具有列表值的字典

python - 如何在 Windows 7 计算机上将模块上传到 Python 测试站点(https ://testpypi. python.org/pypi)?

python - 我如何使用 Twitter 的流 api 中的推文并将它们存储在 mongodb 中

java - 如何从 jython 中的 java 类获取接口(interface)列表?

python - 比较数据框两列中的相同和不同

python -regex匹配单词列表

python - 当我们在Django中使用opencv时如何处理请求

python - 男人脸和女人脸的区别

python-2.7 - 使用 xarray 读取多个坐标