0

For the sake of fun I'm trying to make this work: If I leave the PC, it should lock it after some seconds.

So I'm initializing a Timer and take a Picture every 3 seconds. I calculate the Hashvalue and compare it with the old picture. Here is my testcode:

Timer _timer;
WebCam _webCam;
Bitmap _bitmap;

public CameraChecker()
{
    _webCam = new WebCam();
    _webCam.Connect();
    _timer = new Timer(TimerCb, null, 0, 3000);
}

private void TimerCb(Object stateInfo)
{
    _webCam.Update();
    Bitmap newBitmap = _webCam.CalcBitmap();
    if (_bitmap == null)
        _bitmap = newBitmap;
    else
    {
        ImageConverter conv = new ImageConverter();
        byte[] bytesNew = (byte[])conv.ConvertTo(newBitmap, typeof(byte[]));
        byte[] bytesOld = (byte[])conv.ConvertTo(_bitmap, typeof(byte[]));

        //IStructuralEquatable eqa1 = bytesNew;
        //bool eq = eqa1.Equals(bytesOld, StructuralComparisons.StructuralEqualityComparer);

        //Compute a hash for each image
        SHA256Managed shaM = new SHA256Managed();
        byte[] hash1 = shaM.ComputeHash(bytesNew);
        byte[] hash2 = shaM.ComputeHash(bytesOld);

        //Compare the hash values
        bool eq = true;
        for (int i = 0; i < hash1.Length && i < hash2.Length; i++)
        {
            if (hash1[i] != hash2[i])
            {
                eq = false;
                break;
            }
        }

        if (eq)
        {
            System.Diagnostics.Debugger.Break();
        }
        else
        {
            _bitmap = newBitmap;
        }
    }
}

I'm using the MetriCam SDK to take the Pictures, which seems to work well.
My problem: It never happens that two Pictures have exactly the same value. Even if I try to darken the Camera, it does not seem to work.

As you can see I tried to use the StructuralEquatable, but it didn't work as well.

Was my Test-Project futile?

As usual, thanks for any suggestions or tips!

rudolph9
  • 8,021
  • 9
  • 50
  • 80
Matthias Müller
  • 3,336
  • 3
  • 33
  • 65

1 Answers1

3

The chance you make two excatly te same photos is probably zero. The only other possibility is a hash collision, this alsof close tot zero. So your code is working perfectly. Calculating hashes is not te solution for your problem.

Peter
  • 27,590
  • 8
  • 64
  • 84