[Azure] C# + Azure Face API 作臉部辨識簡單上手
2021-10-29
最近因為在搞事情,需要偵測臉部的 API,以前傳統有解決過這方案我記得是用 OpenCV 之類的,後來看一下了 Azure 有這服務 Azure 人臉辨識
而且這價格對我小量使用來說很便宜,用免費一個月有30,000 免費括打,身為一個客家人看到覺得很可以,所以今天就來試著寫寫看..
1. 首先先去 Azure 申請 Face API ,申請位置 : https://azure.microsoft.com/zh-tw/pricing/details/cognitive-services/face-api/
最後你會拿到 Key , Endpoint ,這兩個很重要,之後你會用到..
2. 之後下載 套件 :
https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Vision.Face/2.7.0-preview.1
記得搶鮮版,要打勾
3.之後就是程式碼的部分,基本上 這是我的 sample 圖片
圖片下載來源: https://www.pakutaso.com/
這裡面有看到四個人臉,我們可以用 Azure Face API 將臉標示出來,然後存成一個檔案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//需要辨識圖片的位置
var targetIamgePath = AppDomain.CurrentDomain.BaseDirectory + "sample" + System.IO.Path.DirectorySeparatorChar +
"pw13.jpg";
//步驟 1 拿到的 ENDPOINT , KEY
var faceClient = Authenticate(ENDPOINT, SUBSCRIPTION_KEY);
//取圖片轉成 stream
byte[] buff = System.IO.File.ReadAllBytes(targetIamgePath);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buff);
//送往 azure 辨識
var localFaces = faceClient.Face.DetectWithStreamAsync(ms).Result;
List rects = new List();
//結果會有很多,分別拿到 x, y, w ,h 之後記錄下來 放在 rects 裡面
foreach (var face in localFaces)
{
var faceRect = face.FaceRectangle;
Result += "Left:" + faceRect.Left + ",Top:" + faceRect.Top + ",Width:" + faceRect.Width + ",Height:" +
faceRect.Height + "";
rects.Add(new Rectangle(faceRect.Left, faceRect.Top, faceRect.Width, faceRect.Height));
}
ms.Close();
//下面的部分就是,讀取一次圖片,將找出來的人臉畫出來。
System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "output");
var img = Image.FromFile(targetIamgePath);
img = DrawRectsToImage(img, rects.ToArray());
string pathStr = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", "sample2.jpg");
img.Save(pathStr);
public static IFaceClient Authenticate(string endpoint, string key)
{
return new FaceClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint };
}
///
/// 將抓到的臉標示上紅框
///
///
///
///
private Image DrawRectsToImage(Image img, System.Drawing.Rectangle[] rects)
{
if (img == null)
{
return null;
}
Result += "ImgW:" + img.Width + "ImgH: " + img.Height + " ";
if (rects != null)
{
Pen redPen = new Pen(Color.Red, 10);
foreach (var rect in rects)
{
var nRect = new Rectangle(rect.Left, rect.Top, rect.Width, rect.Height);
Graphics graphic = Graphics.FromImage(img);
graphic.DrawRectangle(redPen, nRect);
}
return img;
}
結果:
是不是很簡單跟溫馨,當然這操作很簡單,只是為了先測試,之後有玩到什麼騷操作我再來分享..
reference:
https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Vision.Face/2.7.0-preview.1
https://azure.microsoft.com/zh-cn/pricing/details/cognitive-services/face-api/
https://github.com/azure-samples/cognitive-services-vision-face-finder/tree/master/