Better way to compare neighboring cells in matrix

Posted by HyperCube on Stack Overflow See other posts from Stack Overflow or by HyperCube
Published on 2012-12-13T10:24:23Z Indexed on 2012/12/13 11:05 UTC
Read the original article Hit count: 164

Filed under:
|
|
|
|

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 do a similar task... Do you have some suggestions how this can be done in a more efficient manner? Is this even possible?

© Stack Overflow or respective owner

Related posts about python

Related posts about matlab