3

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
indranil pal
  • 221
  • 1
  • 3
  • 8
  • You mean just detect how much light is in the room the webcam can view? Just take a picture from it using WIA or some other library, then look at the pixels to determine how dark or light it is. – 0_______0 Sep 01 '12 at 20:08
  • Thanks for the reply..I will search and understand use of WIA, I am also looking if Aforge .net can help or not. But can you help me understand how I can determine it by the pixels? – indranil pal Sep 02 '12 at 16:11

1 Answers1

2

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.

Community
  • 1
  • 1
0_______0
  • 547
  • 3
  • 11
  • Thanks for the reply, this will work out for the brightness part. From your previous comment I was searching for WIA and how it can be useful to access cam and found out this article http://social.msdn.microsoft.com/Forums/en-US/tailoringappsfordevices/thread/38ce76d0-8d1f-4c20-a06e-67a9a919c9ee - This says that WIA is not supported in Windows 8 :( – indranil pal Sep 03 '12 at 06:53
  • @indranilpal If you read your link, Rob Caplan says "The question and answer were specific to Metro style apps. WIA is supported for Desktop apps.". It works on Windows 8, just not on Metro apps, normal dekstop apps can use WIA. Also, there are plenty of libraries out there as well for accessing webcams. – 0_______0 Sep 03 '12 at 14:56
  • Yes, I overlooked that part... it does support the desktop mode. I will try to implement it and let you know if I face any issues. – indranil pal Sep 03 '12 at 17:57