title: Efficient algorithm for pixel neighborhood difference in OpenCV
body: <p>I was reading <a href="http://www.eecs.qmul.ac.uk/~cfshan/papers/shan-etal-pr07.pdf" rel="nofollow">this</a> and <a href="http://www.research.att.com/people/Gibbon_David_C/library/publications/dg19960101120000.pdf" rel="nofollow">this</a> paper about hand/head tracking. They both talk about detecting motion computing the difference in a neighborhood of each pixel and comparing the result with a threshold:</p>
  
  <p>Quoting from the first paper:</p>
  
  <blockquote>
    <p>We use the temporal differencing method described in Ref. [41], which computes the absolute value of differences in the neighborhood surrounding each pixel, and then derive the accumulated differ- ence by summing the difference of all neighboring pixels. When the accumulated difference is above a predetermined thresh- old, the pixel is assigned to the moving region. </p>
  </blockquote>
  
  <p>Is there an efficient way to do it (possibly in OpenCV)? <br>
  The code I wrote is pretty naive and, besides losing the real-time, seems not to give better results than a simpler pixel-to-pixel difference:</p>
  
  <pre><code>template&lt;class T&gt; class Image {
  private:
      IplImage* imgp;
  public:
      Image(IplImage* img=0) {imgp=img;}
      ~Image(){imgp=0;}
      void operator=(IplImage* img) {imgp=img;}
      inline T* operator[](const int rowIndx) {
          return ((T *)(imgp-&gt;imageData + rowIndx*imgp-&gt;widthStep));}
  };
  
  typedef Image&lt;unsigned char&gt;  BwImage;
  typedef Image&lt;float&gt;          BwImageFloat;
  
  
  void computeMovingRegion( IplImage* prev,  IplImage* cur, IplImage *mov) {
  
      BwImage _prev(prev);
      BwImage _cur(cur);
      BwImage _mov(mov);
  
      for (int i = 3; i&lt;prev-&gt;height-3; i++) {
          for (int j=3; j&lt;prev-&gt;width-3; j++) {
  
              int res=0;
  
              for (int k=i-3; k&lt;i+3; k++) 
                  for (int n=j-3; n&lt;j+3; n++) 
                      res += abs(_cur[k][n] -_prev[k][n]);
  
              if (res&gt;2000) {
                  _mov[i][j]=_cur[i][j];
              }
              else
                  _mov[i][j]=0;
  
          }
      }
  }
  </code></pre>
  
  <p>Images are in grayscale. Don't think it matters, but I'm using MacOS 10.8 and Xcode 4.4.2.</p>