Search code examples
c#motion-detection

Color resemblance for motion detection


Given 2 consecutive frames, how can I search for pixels that changed? I tried the following:

        if (old != null)
        {
            for (int i = 0; i < b.Width; i++)
            {
                for (int j = 0; j < b.Height; j++)
                {
                    if (!b.GetPixel(i, j).Equals(old.GetPixel(i, j)))
                        s.SetPixel(i, j, b.GetPixel(i, j));
                    else
                        s.SetPixel(i, j, Color.White);
                }
            }
        }

Where "old" is the previous frame and "s" is the new frame. The code basically paints the pixels that didn't change in white. But since the webcam produces a very low quality frame almost all of the pixels change. How can I eliminate the pixels that didn't change "greatly"?


Solution

  • A very basic approach is to convert your Color pixel to an 0 - 255 based grey value. So you can compare your pixels as an integer and make some delta error difference.

    Consider this method which convert a color to a integer grayscale value

    private static int GreyScaleRange(Color originalColor) 
    {
      return (int)((originalColor.R * .3) + (originalColor.G * .59)
                 + (originalColor.B * .11));
    }
    

    So instead of doing equal function, you should do

     int deltadifference = 5 ;
    
     if (Math.abs((GreyScaleRange(b.GetPixel(i, j)) - (GreyScaleRange(old.GetPixel(i, j)) > deltadifference)
          s.SetPixel(i, j, b.GetPixel(i, j));
     else
          s.SetPixel(i, j, Color.White);