fastest way to select 7*7 neighbor pixels for every pixel in an image in Python

Viewed 4245

need to read an image as an array and for each pixel select 7*7 neighbor pixels then reshape it and put as a first row of training set:

  import numpy as np
  from scipy import misc
  face1=misc.imread('face1.jpg') 

face1 dimensions are (288, 352, 3) , need to find 7*7 neighbor pixels for every pixel , so 49*3 color then reshape it as a (1,147) array and stack it into an array for all pixels , i took the following approach:

X_training=np.zeros([1,147] ,dtype=np.uint8)
for i in range(3, face1.shape[0]-3):
    for j in range(3, face1.shape[1]-3):
        block=face1[i-3:i+4,j-3:j+4]
        pxl=np.reshape(block,(1,147))
        X_training=np.vstack((pxl,X_training))

resulting X_training shape is (97572, 147)

and as last row contains all zeros then:

a = len(X_training)-1
X_training = X_training[:a]

above code works well for one picture but with Wall time: 5min 19s i have 2000 images, so it will take ages to do it for all the images. I am looking for a faster way to iterate over every pixel and do the above task.

Edit: enter image description here this is what i mean by neighbor pixels , for every pixel face1[i-3 : i+4 ,j-3:j+4]

3 Answers
Related