Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Webcam as ambient light sensor in PC

Is it possible to make the webcam of a pc acting as an ambient light sensor? I am using .Net 4.5 framework in Windows 8 pro.

like image 923
indranil pal Avatar asked Dec 18 '25 03:12

indranil pal


1 Answers

Philippe's answer to this question: How to calculate the average rgb color values of a bitmap has code that will calculate the average RGB values of a bitmat image (bm in his code):

BitmapData srcData = bm.LockBits(
        new Rectangle(0, 0, bm.Width, bm.Height), 
        ImageLockMode.ReadOnly, 
        PixelFormat.Format32bppArgb);

int stride = srcData.Stride;

IntPtr Scan0 = dstData.Scan0;

long[] totals = new long[] {0,0,0};

int width = bm.Width;
int height = bm.Height;

unsafe
{
  byte* p = (byte*) (void*) Scan0;

  for (int y = 0; y < height; y++)
  {
    for (int x = 0; x < width; x++)
    {
      for (int color = 0; color < 3; color++)
      {
        int idx = (y*stride) + x*4 + color;

        totals[color] += p[idx];
      }
    }
  }
}

int avgR = totals[0] / (width*height);
int avgG = totals[1] / (width*height);
int avgB = totals[2] / (width*height);

Once you have the average RGB values you can use Color.GetBrightness to determine how light or dark it is. GetBrightness will return a number between 0 and 1, 0 is black, 1 is white. You can use something like this:

Color imageColor = Color.FromARGB(avgR, avgG, avgB);
double brightness = imageColor.GetBrightness();

You could also convert the RGB values to HSL and look at the "L", that may be more accurate, I don't know.

like image 134
0_______0 Avatar answered Dec 19 '25 21:12

0_______0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!