python - Find a 3x3 sliding window over an image -


i have image.

i want obtain 3x3 window (neighbouring pixels) every pixel in image.

i have python code:

for x in range(2,r-1,1):     y in range(2,c-1,1):         mask5=numpy.array([cv.get2d(copy_img,x-1,y-1),cv.get2d(copy_img,x-1,y),cv.get2d(copy_img,x-1,y+1),cv.get2d(copy_img,x,y-1),cv.get2d(copy_img,x,y),cv.get2d(copy_img,x,y+1),cv.get2d(copy_img,x+1,y-1),cv.get2d(copy_img,x+1,y),cv.get2d(copy_img,x+1,y+1)])         cent=[cv.get2d(copy_img,x,y)] 

mask5 3x3 window. cent center pixel.

is there more efficient way - i.e. using maps, iterators - 2 nested loops i've used?

this can done faster, reshaping , swapping axes, , repeating on kernel elements, this:

im = np.arange(81).reshape(9,9) print np.swapaxes(im.reshape(3,3,3,-1),1,2) 

this gives array of 3*3 tiles tessalates across surface:

[[[[ 0  1  2]   [[ 3  4  5]   [[ 6  7  8]    [ 9 10 11]    [12 13 14]    [15 16 17]    [18 19 20]]   [21 22 23]]   [24 25 26]]]   [[[27 28 29]   [[30 31 32]   [[33 34 35]    [36 37 38]    [39 40 41]    [42 43 44]    [45 46 47]]   [48 49 50]]   [51 52 53]]]   [[[54 55 56]   [[57 58 59]   [[60 61 62]    [63 64 65]    [66 67 68]    [69 70 71]    [72 73 74]]   [75 76 77]]   [78 79 80]]]] 

to overlapping tiles need repeat 8 further times, 'wrapping' array, using combination of vstack , column_stack. note right , bottom tile arrays wrap around (which may or may not want, depending on how treating edge conditions):

im =  np.vstack((im[1:],im[0])) im =  np.column_stack((im[:,1:],im[:,0])) print np.swapaxes(im.reshape(3,3,3,-1),1,2)  #output: [[[[10 11 12]   [[13 14 15]   [[16 17  9]    [19 20 21]    [22 23 24]    [25 26 18]    [28 29 30]]   [31 32 33]]   [34 35 27]]]   [[[37 38 39]   [[40 41 42]   [[43 44 36]    [46 47 48]    [49 50 51]    [52 53 45]    [55 56 57]]   [58 59 60]]   [61 62 54]]]   [[[64 65 66]   [[67 68 69]   [[70 71 63]    [73 74 75]    [76 77 78]    [79 80 72]    [ 1  2  3]]   [ 4  5  6]]   [ 7  8  0]]]] 

doing way wind 9 sets of arrays, need zip them together. this, , reshaping generalises (for arrays dimensions divisible 3):

def new(im):     rows,cols = im.shape     final = np.zeros((rows, cols, 3, 3))     x in (0,1,2):         y in (0,1,2):             im1 = np.vstack((im[x:],im[:x]))             im1 = np.column_stack((im1[:,y:],im1[:,:y]))             final[x::3,y::3] = np.swapaxes(im1.reshape(rows/3,3,cols/3,-1),1,2)     return final 

comparing new function looping through slices (below), using timeit, 4 times faster, 300*300 array.

def old(im):     rows,cols = im.shape     s = []     x in xrange(1,rows):         y in xrange(1,cols):             s.append(im[x-1:x+2,y-1:y+2])     return s 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -