title: Is it possible to vectorize a function that access different elements in an numpy array?
body: <p>Let's say that I wish to implement the following code in python</p>
  
  <p>This function takes an image as 1 dimensional array, and iterates over individual elements in the array (pixels in the input image) which affects an output array that is also an image represented as a 1 dimensional array</p>
  
  <p>example: 
  a single pixel in the input image (red) affects 8 surrounding pixels in (orange)
   <a href="https://i.stack.imgur.com/ewc8W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ewc8W.png" alt="example 1"></a></p>
  
  <p>A basic implementation in C is  </p>
  
  <pre><code>/* C version 
   * Given an input image create an 
   * output image that is shaped by individual pixels
   * of the input image
   */
  
  int image[width * height]; //image retrieved elsewhere
  int output [width * height]; //output image
  int y = 0, x = 0;
  for( y = 1; y &lt; height-1 ; ++ y) {
      for(x = 1; x &lt; width-1; ++ x) {
          if (image[y * width + x] &gt; condition) {
              /* pixel affects the surrounding 8 pixels in the output image */
  
              output[(y-1) * width + x - 1]++; /* upper left  */
              output[(y-1) * width + x    ]++; /* above       */
              output[(y-1) * width + x + 1]++; /* upper right */
              output[y * width + x + 1    ]++; /* right       */
              output[y * width + x - 1    ]++; /* left        */
              output[(y+1) * width + x - 1]++; /* lower left  */
              output[(y+1) * width + x    ]++; /* below       */
              output[(y+1) * width + x + 1]++; /* lower right */
  
  
          }
      }
  }
  </code></pre>
  
  <p>the naive approach in python would be to use the exactly the same element wise access as shown below</p>
  
  <pre><code>#Python version
  input  = blah # formed elsewhere  
  output = np.zeros(width * height)
  for y in xrange(1, height-1):
      for x in xrange(1, width-1):
          if input[y * width + x] &gt; condition:
              output[(y-1) * width + x - 1]+= 1; # upper left  
              output[(y-1) * width + x    ]+= 1; # above       
              output[(y-1) * width + x + 1]+= 1; # upper right 
              output[y * width + x + 1    ]+= 1; # right       
              output[y * width + x - 1    ]+= 1; # left        
              output[(y+1) * width + x - 1]+= 1; # lower left  
              output[(y+1) * width + x    ]+= 1; # below       
              output[(y+1) * width + x + 1]+= 1; # lower right 
  </code></pre>
  
  <p>is there a better way to implement this? Is is possible to vectorize this function?</p>