我正在尝试创建一个函数(或一系列函数),它们执行以下操作:
对于每个单元格A [i,j],具有输入数组(A),提取具有自定义大小的窗口(W),其中值为“min”和“#”。将是:
min = np.min(W)
输出矩阵(H)将值存储为:
H [i,j] = A [i,j] - min(W)
为了更容易理解这个问题,我附上了一张图片(例子):
我目前的代码是:
def res_array(matrix, size):
result = []
sc.generic_filter(matrix, nothing, size, extra_arguments=(result,), mode = 'nearest')
mat_out = result
return mat_out
def local(window):
H = np.empty_like(window)
w = res_array(window, 3)
win_min = np.apply_along_axis(min, 1, w)
# This is where I think it's broken
for k in win_min:
for i in range(window.shape[0]):
for j in range(window.shape[1]):
h[i, j] = window[i,j] - k
k += 1
return h
def nothing(window, out):
list = []
for i in range(window.shape[0]):
list.append(window[i])
out.append(list)
return 0
test = np.ones((10, 10)) * np.arange(10)
a = local(test)
对于输入矩阵A的每个单元格或测试,我需要将代码传递给win_min'中的k的下一个值。
编辑:我想到了直接访问' win_min'的索引,并按1增加,就像我在这里看到的那样:Increment the value inside a list element,但我不知道如何这样做。
感谢您的帮助!
答案 0 :(得分:1)
N=4 #matrix size
a=random((N,N)) #input
#--window size
wl=1 #left
wr=1 #right
wt=1 #top
wb=1 #bottom
#---
H=np.zeros((N,N)) #output
def h(k,l): #individual cell function
#--- checks to not run out of array
k1=max(k-wt,0)
k2=min(k+wb+1,N)
l1=max(l-wl,0)
l2=min(l+wr,N)
#---
return a[k,l]-np.amin(a[k1:k2,l1:l2])
H=array([[h(k,l) for l in range(N)] for k in range(N)]) #running over all matrix elements
print a
print H