如何在python中对2D图像进行中值处理?

时间:2016-10-17 23:27:39

标签: python arrays numpy

我有一个尺寸为WIDTHxHEIGHT的2D numarray。我想通过找到每个bin的中值来对数组进行bin化,以便得到的数组是WIDTH / binsize x HEIGHT / binsize。假设WIDTH和HEIGHT都可以被binsize整除。 编辑:附图中给出了一个例子。

我找到了解决方案,其中binned数组值是每个bin中各个元素的总和或平均值: How to bin a 2D array in numpy?

但是,如果我想在每个bin中进行元素的中间组合,我就无法找到解决方案。非常感谢您的帮助!

编辑:添加了图片 An example of the initial array and desired resultant median binned array

1 个答案:

答案 0 :(得分:1)

所以你正在寻找中位数跨度重塑:

import numpy as np
a = np.arange(24).reshape(4,6)

def median_binner(a,bin_x,bin_y):
    m,n = np.shape(a)
    strided_reshape = np.lib.stride_tricks.as_strided(a,shape=(bin_x,bin_y,m//bin_x,n//bin_y),strides = a.itemsize*np.array([(m / bin_x) * n, (n / bin_y), n, 1]))
    return np.array([np.median(col) for row in strided_reshape for col in row]).reshape(bin_x,bin_y)



print "Original Matrix:"
print a
print "\n"
bin_tester1 = median_binner(a,2,3)
print "2x3 median bin :"
print bin_tester1
print "\n"
bin_tester2 = median_binner(a,2,2)
print "2x2 median bin :"
print bin_tester2

结果:

Original Matrix:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]]


2x3 median bin :
[[  3.5   5.5   7.5]
 [ 15.5  17.5  19.5]]


2x2 median bin :
[[  4.   7.]
 [ 16.  19.]]

阅读this以完全理解代码中的以下行:

strided_reshape = np.lib.stride_tricks.as_strided(a,shape=(bin_x,bin_y,m//bin_x,n//bin_y),strides = a.itemsize*np.array([(m / bin_x) * n, (n / bin_y), n, 1]))