1

Possible Duplicate:
Numpy/Python: Array iteration without for-loop

Suppose I have a matrix of size 100x100 and I would like to compare each pixel to its direct neighbor (left, upper, right, lower) and then do some operations on the current matrix or a new one of the same size. A sample code in Python/Numpy could look like the following: (the comparison >0.5 has no meaning, I just want to give a working example for some operation while comparing the neighbors)

import numpy as np
my_matrix = np.random.rand(100,100)
new_matrix = np.array((100,100))
my_range = np.arange(1,99)
for i in my_range:
    for j in my_range:

        if my_matrix[i,j+1] > 0.5:
            new_matrix[i,j+1] = 1

        if my_matrix[i,j-1] > 0.5:
            new_matrix[i,j-1] = 1

        if my_matrix[i+1,j] > 0.5:
            new_matrix[i+1,j] = 1

        if my_matrix[i-1,j] > 0.5:
            new_matrix[i-1,j] = 1

        if my_matrix[i+1,j+1] > 0.5:
            new_matrix[i+1,j+1] = 1

        if my_matrix[i+1,j-1] > 0.5:
            new_matrix[i+1,j-1] = 1

        if my_matrix[i-1,j+1] > 0.5:
            new_matrix[i-1,j+1] = 1

This can get really nasty if I want to step into one neighboring cell and start from it to compare it to its neighbors ... Do you have some suggestions how this can be done in a more efficient manner? Is this even possible?

4

2 回答 2

2

我不是 100% 确定你的代码的目标是什么,忽略边界处的索引问题相当于

new_matrix = my_matrix > 0.5

但是您可以使用形态学运算快速完成这些计算的高级版本:

import numpy as np
from scipy.ndimage import morphology

a = np.random.rand(5,5)
b = a > 0.5

element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
result = morphology.binary_dilation(b, element) * 1
于 2012-12-13T10:32:09.440 回答
0

防止这种情况“变得讨厌”的方法是:将邻居检查代码封装在一个函数中。然后你可以在必要时用邻居的坐标调用它。

如果您需要跟踪检查过的对,以免保留相同的对,请在此基础上使用某种记忆。

于 2012-12-13T13:40:29.517 回答