Skip to content

Instantly share code, notes, and snippets.

@lisysolution
Created November 7, 2016 14:25
Show Gist options
  • Save lisysolution/2b2e49eb7eee36f375fe5712a54112f8 to your computer and use it in GitHub Desktop.
Save lisysolution/2b2e49eb7eee36f375fe5712a54112f8 to your computer and use it in GitHub Desktop.
MS Faces API를 이용하여 사진에서 얼굴 추출 후 Blur 처리 하기
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ImageProcessorCore;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
/*
http://www.sysnet.pe.kr/2/0/11095
PM> Install-Package Microsoft.ProjectOxford.Face
PM> Install-Package ChyImageProcessorCore -Pre
PM> Install-Package System.Numerics.Vectors -Pre
PM> Install-Package System.Runtime.CompilerServices.Unsafe
API 키 발급
https://www.microsoft.com/cognitive-services/en-us/sign-up
*/
public class Program
{
public static void Main(string[] args)
{
const string sourceImage = @"...원본 이미지 파일 경로...";
const string destinationImage = @"...대상 이미지 파일 경로...";
var detects = DetectFaces(sourceImage, "...API키...");
var faceRects = detects.Result;
Console.WriteLine($"Detected {faceRects.Length} faces");
BlurFaces(faceRects, sourceImage, destinationImage);
Console.WriteLine($"Done!!!");
Console.ReadKey();
}
private static void BlurFaces(FaceRectangle[] faceRects, string sourceImage, string destinationImage)
{
if (File.Exists(destinationImage))
{
File.Delete(destinationImage);
}
if (faceRects.Length > 0)
{
using (FileStream stream = File.OpenRead(sourceImage))
using (FileStream output = File.OpenWrite(destinationImage))
{
var image = new Image<Color, uint>(stream);
foreach (var faceRect in faceRects)
{
var rectangle = new Rectangle(
faceRect.Left,
faceRect.Top,
faceRect.Width,
faceRect.Height);
image = image.BoxBlur(20, rectangle);
}
image.SaveAsJpeg(output);
}
}
}
private static async Task<FaceRectangle[]> DetectFaces(string imageFilePath, string apiKey)
{
var faceServiceClient = new FaceServiceClient(apiKey);
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];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment