Skip to content

Instantly share code, notes, and snippets.

@3t14
Last active January 28, 2017 02:46
Show Gist options
  • Save 3t14/56dc9a8f4068f0833c25f0a0c8b0d1e0 to your computer and use it in GitHub Desktop.
Save 3t14/56dc9a8f4068f0833c25f0a0c8b0d1e0 to your computer and use it in GitHub Desktop.
using System;
using Microsoft.ProjectOxford.Face;
using Plugin.Media;
using Xamarin.Forms;
namespace HelloFaceAPI
{
public class App : Application
{
// 後の参照用
Image photoImage;
public App()
{
photoImage = new Image { };
var button = new Button
{
Text = "写真撮影する"
};
// The root page of your application
var content = new ContentPage
{
Title = "HelloCamera",
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
HorizontalTextAlignment = TextAlignment.Center,
Text = "写真撮影サンプル"
},
button,
photoImage
}
}
};
button.Clicked += async (sender, e) =>
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable
|| !CrossMedia.Current.IsTakePhotoSupported)
{
await content.DisplayAlert("警告", "カメラデバイスが使えません", "OK");
}
// 写真撮影する
var file = await CrossMedia.Current.TakePhotoAsync(
// 引数は保存条件を指定
new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Photos", // 保存フォルダ名
Name = "sample.jpg", // 保存ファイル名。
// 既存の場合は"sample_2.jpg"といったようにナンバリングされる
// SaveToAlbum = true, // この場合はデバイスの写真アルバムに記録
// 写真サイズ、Customの場合はCustomPhotoSizeで%指定
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
// デフォルトのカメラ指定(FrontもしくはRearで指定
DefaultCamera = Plugin.Media.Abstractions.CameraDevice.Front
}
);
// 撮影に失敗の場合は何もしない
if (file == null) return;
// FromStreamメソッドはストリームを返すメソッドを引数にもつ
photoImage.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream(); // ファイルストリームを取得
//file.Dispose(); // 後の利用のためファイルを解放しない
return stream; // 取得したストリームを引き渡す
});
// 取得した画像をFace APIで解析
var faceClient = new FaceServiceClient("<ここにキーを入力してください。>");
// Azure側に送信し、解析結果を待つ
var result = await faceClient.DetectAsync(file.GetStream(),
returnFaceAttributes: new[]{
FaceAttributeType.Smile, // 笑顔度判定0-1
FaceAttributeType.Age, // 年齢推定
FaceAttributeType.Gender, // 性別判定
FaceAttributeType.Glasses, // メガネ判定
FaceAttributeType.HeadPose, // 頭部ポーズ判定
FaceAttributeType.FacialHair // ヒゲなどの判定
});
// resultはコレクション型。顔に該当するものがないとき0判定
if (result.Length == 0)
{
await content.DisplayAlert("残念", "判定できませんでした。", "OK");
return;
}
await content.DisplayAlert(
"あなたの年齢は",
result[0].FaceAttributes.Age + "歳です", "OK");
await content.DisplayAlert(
"あなたの笑顔度は",
(100 * result[0].FaceAttributes.Smile) + "点です", "OK");
file.Dispose();
};
MainPage = new NavigationPage(content);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment