实例介绍
【实例简介】
【实例截图】
【实例截图】
【核心代码】
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testface
{
public partial class MainForm : Form
{
Thread thread;
public static bool bExit = false;
public static MainForm mainForm;
private float kx, ky;
int videoWidth, videoHeight, ifaceCount;
Dictionary<uint, FaceAttrClass> faceAttrs;
// 设置APPID/AK/SK
string APP_ID = "XXX";
string API_KEY = "XXXX";
string SECRET_KEY = "XXX";
public static Baidu.Aip.Face.Face client;
Bitmap outBitmap;
long sdk_begin;
System.Timers.Timer timer;
string[] strsMorning = {"","","" };
Image loadingImage;
public MainForm()
{
mainForm = this;
InitializeComponent();
videoWidth = 640;
videoHeight = 480;
kx = (float)pictureBox1.Width / videoWidth;
ky = (float)pictureBox1.Height / videoHeight;
faceAttrs = new Dictionary<uint, FaceAttrClass>();
outBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
timer = new System.Timers.Timer(2000);
loadingImage = Image.FromFile(Application.StartupPath "\\assets\\loading.gif");
}
private void MainForm_Load(object sender, EventArgs e)
{
client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
thread = new Thread(new ThreadStart(Face.FaceMain));
thread.Start();
//Face.test_face_track();
ImageAnimator.Animate(loadingImage, new EventHandler((object o, EventArgs ea) =>
{
lock (this)
{
ImageAnimator.UpdateFrames(o as Image);
}
}));
}
public void UpdateImg(byte[] buf, string res)
{
long t_begin = TimeUtil.get_time_stamp();
long sdk_end = t_begin;
float fontSize;
Bitmap image = Image.FromStream(new MemoryStream(buf)) as Bitmap;
//Bitmap bitmap = new Bitmap(image);
Graphics g = Graphics.FromImage(outBitmap);
g.DrawImage(image, 0,0, pictureBox1.Width, pictureBox1.Height);
//textBox1.Text = res;
dynamic obj = JsonConvert.DeserializeObject<dynamic>(res);
if (obj.errno == 0 && obj.data.count > 0)
{
ifaceCount = obj.data.count;
foreach (dynamic item in obj.data.list)
{
bool bError = false;
int center_x = item.center_x;
int center_y = item.center_y;
float score = item.score;
uint faceId = item.face_id;
int width = item.width;
if (score < 0.8)
continue;
int faceX = (int)((center_x - 2 * width / 3));
if (faceX < 0)
faceX = 0;
else if (faceX > videoWidth)
faceX = videoWidth;
int faceY = (int)((center_y - width * 1.2));
if (faceY < 0)
faceY = 0;
else if (faceY > videoHeight)
faceX = videoHeight;
int faceWidth = (int)(width * 1.3);
if (faceX faceWidth > videoWidth)
faceWidth = videoWidth - faceX;
int faceHeight = (int)(width * 1.8);
if (faceY faceHeight > videoHeight)
faceHeight = videoHeight - faceY;
fontSize = (faceWidth * kx) / 12;
Rectangle rectangle = new Rectangle(faceX, faceY, faceWidth, faceHeight);
Rectangle drawRectangle = new Rectangle((int)(faceX * kx), (int)(faceY * ky), (int)(faceWidth * kx), (int)(faceHeight * ky));
FaceAttrClass temp;
string strBeauty = "未知";
string strAge = "未知";
if (!faceAttrs.TryGetValue(faceId, out temp))
{
if (faceAttrs.Count >= 20)
faceAttrs.Remove(faceAttrs.Keys.Min());
faceAttrs.Add(faceId, new FaceAttrClass()
{
frame = 0,
gifImage = Image.FromFile(Application.StartupPath "\\assets\\loading.gif")
});
ImageAnimator.Animate(faceAttrs[faceId].gifImage, new EventHandler((object o, EventArgs e) =>
{
lock (this)
{
ImageAnimator.UpdateFrames(o as Image);
}
}));
}
else if (temp.frame == 8)
{
try
{
MemoryStream memoryStream = new MemoryStream();
Bitmap bmpCrop = image.Clone(rectangle, System.Drawing.Imaging.PixelFormat.Undefined);
bmpCrop.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
FaceAttrThread faceAttrThread = new FaceAttrThread(memoryStream, faceAttrs, faceId);
new Thread(new ThreadStart(faceAttrThread.Run)).Start();
}
catch (Exception)
{
bError = true;
}
}
faceAttrs[faceId].frame ;
float fillY = drawRectangle.Y - (3 * fontSize) - (fontSize * 0.1f);
g.FillRectangle(new SolidBrush(Color.FromArgb(151, 191, 41, 41)), drawRectangle.X, fillY, drawRectangle.Width, 3 * fontSize);
if (faceAttrs[faceId].frame == 20)
ImageAnimator.StopAnimate(faceAttrs[faceId].gifImage, null);
if (faceAttrs[faceId].frame > 20)
{
strBeauty = faceAttrs[faceId].beauty > 0 ? faceAttrs[faceId].beauty.ToString() : "未知";
strAge = faceAttrs[faceId].age > 0 ? faceAttrs[faceId].age.ToString() : "未知";
label1.Invoke(new EventHandler(delegate
{
label1.Text = "年龄:" strAge;
}));
label1.Invoke(new EventHandler(delegate
{
label2.Text = "颜值:" strBeauty;
}));
}
else
{
lock (this)
{
g.DrawImage(faceAttrs[faceId].gifImage, drawRectangle.X fontSize, fillY, 3 * fontSize, 3 * fontSize);
}
g.DrawString("特征分析中", new Font("宋体", fontSize, GraphicsUnit.Pixel), Brushes.White, drawRectangle.X 4.5f * fontSize, fillY fontSize);
}
}
}
else
ifaceCount = 0;
pictureBox1.CreateGraphics().DrawImage(outBitmap, 0, 0);
}
public void UpdateImgExt(System.Drawing.Bitmap image, TrackFaceInfo[] track_info, int faceCount)
{
long t_begin = TimeUtil.get_time_stamp();
long sdk_end = t_begin;
float fontSize;
uint highestBeauty = uint.MaxValue;
int iBeauty = 0, analysisFaceCount = 0;
videoWidth = image.Width;
videoHeight = image.Height;
kx = (float)pictureBox1.Width / videoWidth;
ky = (float)pictureBox1.Height / videoHeight;
Graphics g = Graphics.FromImage(outBitmap);
g.DrawImage(image, 0, 0, pictureBox1.Width, pictureBox1.Height);
foreach (var item in faceAttrs)
{
faceAttrs[item.Key].valid = false;
}
if (faceCount > 0)
{
this.ifaceCount = faceCount;
foreach (TrackFaceInfo item in track_info)
{
float score = item.score;
if (score < 0.8)
continue;
bool bError = false;
int center_x = (int)item.box.mCenter_x;
int center_y = (int)item.box.mCenter_y;
uint faceId = item.face_id;
int width = (int)item.box.mWidth;
FaceAttrClass temp;
if (!faceAttrs.TryGetValue(faceId, out temp))
{
if (faceAttrs.Count >= 20)
faceAttrs.Remove(faceAttrs.Keys.Min());
faceAttrs.Add(faceId, new FaceAttrClass()
{
frame = 0,
gifImage = loadingImage
});
}
faceAttrs[faceId].faceX = (int)((center_x - 2 * width / 3));
if (faceAttrs[faceId].faceX < 0)
faceAttrs[faceId].faceX = 0;
else if (faceAttrs[faceId].faceX > videoWidth)
faceAttrs[faceId].faceX = videoWidth;
faceAttrs[faceId].faceY = (int)((center_y - width * 1.2));
if (faceAttrs[faceId].faceY < 0)
faceAttrs[faceId].faceY = 0;
else if (faceAttrs[faceId].faceY > videoHeight)
faceAttrs[faceId].faceY = videoHeight;
faceAttrs[faceId].faceWidth = (int)(width * 1.35);
if (faceAttrs[faceId].faceX faceAttrs[faceId].faceWidth > videoWidth)
faceAttrs[faceId].faceWidth = videoWidth - faceAttrs[faceId].faceX;
faceAttrs[faceId].faceHeight = (int)(width * 1.8);
if (faceAttrs[faceId].faceY faceAttrs[faceId].faceHeight > videoHeight)
faceAttrs[faceId].faceHeight = videoHeight - faceAttrs[faceId].faceY;
if (faceAttrs[faceId].frame > 20)
{
if (faceAttrs[faceId].beauty > iBeauty)
{
highestBeauty = faceId;
iBeauty = faceAttrs[faceId].beauty;
}
analysisFaceCount ;
}
faceAttrs[faceId].valid = true;
}
foreach (var item in faceAttrs)
{
if (!item.Value.valid)
continue;
bool bError = false;
uint faceId = item.Key;
int faceX = faceAttrs[faceId].faceX;
int faceY = faceAttrs[faceId].faceY;
int faceWidth = faceAttrs[faceId].faceWidth;
int faceHeight = faceAttrs[faceId].faceHeight;
fontSize = (faceWidth * kx) / 12;
Rectangle rectangle = new Rectangle(faceX, faceY, faceWidth, faceHeight);
Rectangle drawRectangle = new Rectangle((int)(faceX * kx), (int)(faceY * ky), (int)(faceWidth * kx), (int)(faceHeight * ky));
string strBeauty = "未知";
string strAge = "未知";
if (faceAttrs[faceId].frame == 8)
{
try
{
MemoryStream memoryStream = new MemoryStream();
Bitmap bmpCrop = image.Clone(rectangle, System.Drawing.Imaging.PixelFormat.Undefined);
bmpCrop.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
FaceAttrThread faceAttrThread = new FaceAttrThread(memoryStream, faceAttrs, faceId);
new Thread(new ThreadStart(faceAttrThread.Run)).Start();
}
catch (Exception)
{
bError = true;
}
}
faceAttrs[faceId].frame ;;
//g.DrawRectangle(new Pen(Color.Gold, 2), drawRectangle);
float fillY = drawRectangle.Y - (3 * fontSize) - (fontSize * 0.1f);
if(analysisFaceCount >= 2 && faceId == highestBeauty)
g.FillRectangle(new SolidBrush(Color.FromArgb(151, 0xdb, 0x67, 0x34)), drawRectangle.X, fillY, drawRectangle.Width, 3 * fontSize);
else
g.FillRectangle(new SolidBrush(Color.FromArgb(151, 0xbc, 0x6f, 0x6f)), drawRectangle.X, fillY, drawRectangle.Width, 3 * fontSize);
if (faceAttrs[faceId].frame > 20)
{
strBeauty = faceAttrs[faceId].beauty > 0 ? faceAttrs[faceId].beauty.ToString() : "未知";
strAge = faceAttrs[faceId].age > 0 ? faceAttrs[faceId].age.ToString() : "未知";
label1.Invoke(new EventHandler(delegate
{
label1.Text = "年龄:" strAge;
}));
label1.Invoke(new EventHandler(delegate
{
label2.Text = "颜值:" strBeauty;
}));
}
else
{
lock (this)
{
g.DrawImage(faceAttrs[faceId].gifImage, drawRectangle.X fontSize, fillY, 3 * fontSize, 3 * fontSize);
}
g.DrawString("特征分析中", new Font("宋体", fontSize, GraphicsUnit.Pixel), Brushes.White, drawRectangle.X 4.5f * fontSize, fillY fontSize);
}
}
}
else
{
ifaceCount = 0;
faceAttrs.Clear();
}
pictureBox1.CreateGraphics().DrawImage(outBitmap, 0, 0);
}
}
public class FaceAttrThread
{
MemoryStream _memoryStream;
uint _faceId;
Dictionary<uint, FaceAttrClass> _faceAttrs;
public FaceAttrThread(MemoryStream memoryStream, Dictionary<uint, FaceAttrClass> faceAttrs, uint faceId)
{
_memoryStream = memoryStream;
_faceAttrs = faceAttrs;
_faceId = faceId;
}
public void Run()
{
FaceAttrClass temp;
try
{
string image = Convert.ToBase64String(_memoryStream.GetBuffer());
// 如果有可选参数
var options = new Dictionary<string, object>{
{"face_field", "age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype"},
{"max_face_num", 1},
{"face_type", "LIVE"}
};
// 带参数调用人脸检测
dynamic result = MainForm.client.Detect(image, "BASE64", options);
if (result.error_code == 0 && result.result.face_num > 0 && result.result.face_list[0].face_probability > 0.9 && _faceAttrs.TryGetValue(_faceId, out temp))
{
_faceAttrs[_faceId].beauty = (int)(80 0.2 * float.Parse(result.result.face_list[0].beauty.ToString()));
_faceAttrs[_faceId].age = (int)float.Parse(result.result.face_list[0].age.ToString());
_faceAttrs[_faceId].expression = result.result.face_list[0].expression.type.ToString() == "none" ? 0 : 1;
if (result.result.face_list[0].gender.type.ToString() == "male")
_faceAttrs[_faceId].gender = 1;
else if (result.result.face_list[0].gender.type.ToString() == "female")
_faceAttrs[_faceId].gender = 2;
else
_faceAttrs[_faceId].gender = 0;
_faceAttrs[_faceId].glass = result.result.face_list[0].glasses.type.ToString() == "none" ? 0 : 1;
}
}
catch (Exception)
{
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论