title: OpenCV C# Frame Differencing
body: <p>I'm new to computer vision and currently playing around with static frame differencing to try and determine whether there is motion in video.</p>
  <p>My variables:</p>
  <pre><code>public Mat currentFrame = new Mat();
  public Mat prevFrame = new Mat();
  public Mat result = new Mat();
  bool motion = false;
  </code></pre>
  <p>Simple differencing function (being called every frame):</p>
  <pre><code>public Mat getDifference(Mat videoFrame)
  {
      currentFrame = videoFrame.Clone();
      Cv2.Absdiff(currentFrame, prevFrame, result);
      prevFrame = currentFrame.Clone();
      return result;
  }
  </code></pre>
  <p>When motion exists the result matrix looks like this:
  <a href="https://i.stack.imgur.com/Iu8ii.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iu8ii.png" alt="enter image description here" /></a></p>
  <p>When motion doesn't exist the result matrix looks like this (empty):
  <a href="https://i.stack.imgur.com/jrMRT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jrMRT.png" alt="enter image description here" /></a></p>
  <p>My original idea was that if the result matrix is effectively empty (all black), then I could say motion = false. However, this is proving to be more difficult that anticipated since it is technically never empty, so I can't say:</p>
  <pre><code>if(!result.Empty())
  {
      motion = true;
  }
  </code></pre>
  <p>Without the need of for loops and pixel by pixel analysis, is there a simple/clean 'if' statement I can use that simply says (if the matrix contains anything that isn't black pixels, motion = true). Or... is this too simplistic? I'm open to hearing better ways of doing this, I had a look around on the web but there aren't many solid examples for C#. My video is playing within a WPF application in real-time so nested for loops are to be avoided.</p>
  <p>Thanks for your time!</p>