前言
因为疫情的原因,无论是进入商场还是医院、车站,都需要出示健康码。
现在基本都是采取人工方式核验健康码,看到绿码就通过,否则就禁止进入。
但是,单靠人工核验健康码容易造成人员拥堵,增加病毒交叉感染的风险,其实完全可以使用计算机来实现自动核验。
原理
如图所示,健康码其实就是个二维码,里面存储了健康码相关信息。
因此,只需通过摄像头扫描手机界面,识别出手机上的二维码即可。
实现
创建一个WinForm程序,添加下列控件:
-
button 开启摄像头
-
pictureBox 显示摄像头图像
-
time 定时识别摄像头图像,频率设为100
-
label 显示健康码状态
1. 开启摄像头
添加nuget包AForge.Video.DirectShow
,设置button的Click事件:
-
VideoCaptureDevice _camera;
-
private void button1_Click(object sender, EventArgs e)
-
{
-
_camera = new VideoCaptureDevice(new FilterInfoCollection(FilterCategory.VideoInputDevice)[0].MonikerString);
-
_camera.NewFrame += camera_NewFrame;
-
_camera.Start();
-
timer1.Enabled = true;
-
}
-
private void camera_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
-
{
-
//将摄像头每帧图像显示到pictureBox
-
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
-
}
2. 识别二维码
引用nuget包ZXing.Net
,在timer的Tick事件中识别二维码:
-
private void timer1_Tick(object sender, EventArgs e)
-
{
-
if (pictureBox1.Image != null)
-
{
-
var img = (Bitmap)pictureBox1.Image.Clone();
-
var barcodeReader = new BarcodeReader();
-
var result = barcodeReader.Decode(img);
-
if (result != null)
-
{
-
var healthCode = JsonConvert.DeserializeAnonymousType(result.Text,
-
new { Color = "" });
-
if (healthCode != null)
-
{
-
var color = healthCode.Color;
-
if (color == "green")
-
{
-
label1.Text = "绿码";
-
label1.ForeColor = Color.Green;
-
}
-
else if (color == "red")
-
{
-
label1.Text = "红码";
-
label1.ForeColor = Color.Red;
-
}
-
else if (color == "yellow")
-
{
-
label1.Text = "黄码";
-
label1.ForeColor = Color.Yellow;
-
}
-
else
-
{
-
label1.Text = "异常";
-
}
-
}
-
}
-
}
-
}
健康码的内容是一个json字符串,其中Color属性代表健康码状态。
3. 运行效果
运行程序,点击“开启摄像头”,可以正常识别:
结论
健康码的内容不包含时间,因此下一步还需要把更新时间从图片中识别出来,保证是最新的健康码。