Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Spatial Filtering 2d numpy array with a 3x3 mask

  1. Aug 30, 2016 #1
    I have large 2d matrices from dicom files that i wish to filter with a 3x3 mask. the image arrays are of varying size and are padded with one border of zeros for the edge handling of the mask. i need to iterate over every element in the array and multiply it by the mask. ive done it in SciLab but so far in python i have the padded image matrix and the 3x3 mask ready to go i just need to get the syntax right.

    g is the image matrix usually about 600 by 800, i.e. not square
    w is the 3x3 filter

    the function is SciLab is as follows

    Code (Text):
      for i=1:m;
            for j=1:n;
                   g(i,j)= g(i,j)*w(1,1)+g(i+1,j)*w(2,1)+g(i+2,j)*w(3,1)...
    i, j and m,n refers to the array elements of the image matrix and the filter but it doesnt work like that in python.

    Im just having trouble with the syntax conversions.

  2. jcsd
  3. Aug 30, 2016 #2
    You'll need something like

    Code (Python):

    for i in range(1,m):
        for j in range(1,n):
             g[i][j] = g[i][j] * w[1][1]+g[i+1][j]* etc etc etc
    couple things to check when you do this,
    make sure you haven't mixed up your rows/columns. I've done that before and its easy to miss (I mean make sure it shouldn't be g[ i])
    Also the lists in python generally start at 0, so you may want to have range(0, m) instead of range(1,m)

    Hope that helps
    Last edited by a moderator: Aug 30, 2016
  4. Aug 30, 2016 #3
    thanks, that will help..
    just out of curiosity... does the ndimage.convolve method from scipy do the filtering in the same way? that would make it a one liner...
  5. Aug 30, 2016 #4

    Never used it. Try it out and see if it does :)
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted