...
public void TrainRecognizer()
{
var allFaces = new FRService().All();
if (allFaces.Count > 0)
{
var faceImages = new Image<Gray, byte>[allFaces.Count];
var faceLabels = new int[allFaces.Count];
for (int i = 0; i < allFaces.Count; i++)
{
Stream stream = new MemoryStream();
stream.Write(allFaces[i].Face, 0, allFaces[i].Face.Length);
var faceImage = new Image<Gray, byte>(new Bitmap(stream));
faceImages[i] = faceImage.Resize(100, 100, Inter.Cubic);
faceLabels[i] = (int)(allFaces[i].Id);
}
// can also try :LBPHFaceRecognizer
var fr = new EigenFaceRecognizer();
fr.Train(faceImages, faceLabels);
var retPath = ConfigurationManager.AppSettings["trainedPath"];
var savedFile = retPath + $"{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}_frModel";
fr.Save(savedFile);
MessageBox.Show($"Model trained successfully. saved into {savedFile}");
}
else
{
MessageBox.Show("No face found in db");
}
}
...
人脸数据服务类
public class FRService
{
public bool Enroll(UserFace record, out string error)
{
error = "";
try
{
using (var context = new EmguFRContext())
{
var existing = context.UserFaces.FirstOrDefault(x => x.UserName == record.UserName);
if (existing != null)
{
context.UserFaces.Remove(existing);
}
context.UserFaces.Add(record);
context.SaveChanges();
}
return true;
}
catch (DbEntityValidationException ex)
{
error = ex.Message;
if (ex.InnerException != null)
{
error += "\r\n" + ex.InnerException;
}
return false;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
public IList<UserFace> All()
{
try
{
using (var context = new EmguFRContext())
{
var all = context.UserFaces.ToList();
return all;
}
}
catch (Exception ex)
{
return new List<UserFace>();
}
}
}
public partial class EmguFRContext : DbContext
{
public EmguFRContext()
: base("name=FRDataContext")
{
}
public virtual DbSet<UserFace> UserFaces { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
[Table("UserFace")]
public partial class UserFace
{
public long Id { get; set; }
[StringLength(50)]
public string UserName { get; set; }
[Column(TypeName = "image")]
public byte[] Face { get; set; }
}