微軟認知服務——人臉識別
之前做微軟編程之美的時候接觸了下微軟認知服務相應的api,但沒有仔細研究。最近在做計算機視覺相關的內容,正好順着文檔寫了一個demo。
申請API
人臉識別API:https://www.azure.cn/cognitive-services/zh-cn/face-api
可以用你的微軟賬號申請免費試用,申請之后會得到相應的密鑰。
搭建demo
我使用的平台是Visual Studio 2013,而不是文檔中要求的Visual Studio 2015。使用的語言是C#,用WPF搭建一個簡單的界面。
在WPF下加入如下結構:
<Grid x:Name="BackPanel">
<Image x:Name="FacePhoto" Stretch="Uniform" Margin="0,0,0,30"/>
<Button x:Name="BrowseButton" Margin="20,5" Height="20" VerticalAlignment="Bottom" Content="Browse..." Click="BrowseButton_Click"/>
</Grid>
在解決方案資源管理器中右鍵你的解決方案名稱,打開管理NuGet程序包,搜索Netonsoft.json和Microsoft.ProjectOxford.Face,分別安裝。
在MainWindow.xaml.cs中:
添加你的密鑰:
private readonly IFaceServiceClient faceServiceClient = new FaceServiceClient("你的密鑰");
編寫對上傳照片檢測人臉的代碼,如下:
private async Task<FaceRectangle[]> UploadAndDetectFaces(string imageFilePath)
{
try
{
using (Stream imageFileStream = File.OpenRead(imageFilePath))
{
var faces = await faceServiceClient.DetectAsync(imageFileStream);
var faceRects = faces.Select(face => face.FaceRectangle);
return faceRects.ToArray();
}
}
catch (Exception)
{
return new FaceRectangle[0];
}
}
添加button的Click事件,並添加async關鍵字,如下:
private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openDlg = new Microsoft.Win32.OpenFileDialog();
openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
bool? result = openDlg.ShowDialog(this);
if (!(bool)result)
{
return;
}
string filePath = openDlg.FileName;
Uri fileUri = new Uri(filePath);
BitmapImage bitmapSource = new BitmapImage();
bitmapSource.BeginInit();
bitmapSource.CacheOption = BitmapCacheOption.None;
bitmapSource.UriSource = fileUri;
bitmapSource.EndInit();
FacePhoto.Source = bitmapSource;
Title = "Detecting...";
FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath);
Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length);
if (faceRects.Length > 0)
{
DrawingVisual visual = new DrawingVisual();
DrawingContext drawingContext = visual.RenderOpen();
drawingContext.DrawImage(bitmapSource,
new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
double dpi = bitmapSource.DpiX;
double resizeFactor = 96 / dpi;
foreach (var faceRect in faceRects)
{
drawingContext.DrawRectangle(
Brushes.Transparent,
new Pen(Brushes.Red, 2),
new Rect(
faceRect.Left * resizeFactor,
faceRect.Top * resizeFactor,
faceRect.Width * resizeFactor,
faceRect.Height * resizeFactor
)
);
}
drawingContext.Close();
RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
(int)(bitmapSource.PixelWidth * resizeFactor),
(int)(bitmapSource.PixelHeight * resizeFactor),
96,
96,
PixelFormats.Pbgra32);
faceWithRectBitmap.Render(visual);
FacePhoto.Source = faceWithRectBitmap;
}
}
運行結果
初始界面:
打開照片:
圖片來源:網上搜索
檢測結果:
可以看到有兩個人臉並沒有很好地識別出來,具體的參數是可以獲取到的,需要進一步研究。