Files
JoyD/Windows/CS/Framework4.0/Camera/Camera/LedDetector.cs
2026-03-26 22:54:14 +08:00

46 lines
1.3 KiB
C#

using System;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
public enum LedState { Off, On }
public enum LedColor { Unknown, Red, Green, Blue }
public class LedDetector
{
public Tuple<LedState, LedColor> Detect(Image<Bgr, byte> image, Rectangle roi)
{
using (Image<Bgr, byte> subImg = image.GetSubRect(roi))
using (Image<Hsv, byte> hsv = subImg.Convert<Hsv, byte>())
{
Image<Gray, byte> H = hsv[0];
Image<Gray, byte> S = hsv[1];
Image<Gray, byte> V = hsv[2];
double avgH = CvInvoke.Mean(H).V0;
double avgS = CvInvoke.Mean(S).V0;
double avgV = CvInvoke.Mean(V).V0;
H.Dispose();
S.Dispose();
V.Dispose();
bool isOff = (avgS < 38) || (avgV < 55);
if (isOff)
return new Tuple<LedState, LedColor>(LedState.Off, LedColor.Unknown);
LedColor color = LedColor.Unknown;
if ((avgH >= 0 && avgH <= 10) || (avgH >= 170 && avgH <= 180))
color = LedColor.Red;
else if (avgH >= 35 && avgH <= 75)
color = LedColor.Green;
else if (avgH >= 90 && avgH <= 130)
color = LedColor.Blue;
return new Tuple<LedState, LedColor>(LedState.On, color);
}
}
}