Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

주간 닷넷에 소개된,

주간닷넷 2016년 8월 2일
; https://learn.microsoft.com/en-us/archive/blogs/eva/%EC%A3%BC%EA%B0%84%EB%8B%B7%EB%84%B7-2016%EB%85%84-8%EC%9B%94-2%EC%9D%BC

내용 중에 다음의 것을 한번 실습해 보았습니다. ^^

Detect and Blur Faces with .NET Core and Face API
; https://carlos.mendible.com/2016/07/30/detect-and-blur-faces-with-dotnetcore-and-face-api/

위의 내용에 소개된 Face API는 마이크로소프트가 Azure를 통해 서비스하는 "Cognitive Services" 중의 하나입니다. 따라서 이 API를 사용하려면 APIKey를 받아야 하고 그러려면 다음의 페이지에서 구독 신청을 해야 합니다.

Cognitive Services - Get started for free
; https://www.microsoft.com/cognitive-services/en-us/sign-up

그럼 다양한 서비스를 신청할 수 있는데,

Cognitive Services - Request new trials
; https://azure.microsoft.com/en-us/services/cognitive-services/

Face API의 경우 (분당 20건의 제한으로) 월 3만 건의 호출을 무료로 사용할 수 있습니다.

어쨌든, 신청을 하면 API Key를 받았을 테고 시작해 보겠습니다. ^^




사실 모든 순서는 "Detect and Blur Faces with .NET Core and Face API" 글에 잘 나와 있습니다. 하지만, .NET Core를 바탕으로 하고 있는데, 그냥 윈도우 응용 프로그램에도 쉽게 적용할 수 있습니다.

제 경우에는 윈도우 콘솔 프로그램으로 시작해 보겠습니다. 프로젝트 만든 후, NuGet을 통해 "Microsoft Cognitive Services Face API"와 함께 관련 라이브러리를 참조 추가합니다.

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 

그다음 App.config에 Face API Key를 입력해 설정해 두고,

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <appSettings>
        <add key="FaceAPIKey" value="...[your_face_api_key]..." />
    </appSettings>
</configuration>

"Detect and Blur Faces with .NET Core and Face API" 글의 소스 코드를 그대로 적용하시면 됩니다.

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ImageProcessorCore;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
using System.Configuration;

public class Program
{
    const string sourceImage = "face_blur_1.png";

    public static void Main(string[] args)
    {
        const string destinationImage = "detectedfaces.jpg";

        var detects = DetectFaces(sourceImage, ConfigurationManager.AppSettings["FaceAPIKey"]);
        var faceRects = detects.Result;

        Console.WriteLine($"Detected {faceRects.Length} faces");

        BlurFaces(faceRects, sourceImage, destinationImage);

        Console.WriteLine($"Done!!!");
    }

    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];
        }
    }
}

직접 실습을 해봤는데, 좀 실망(?!)스럽군요. 아래는 원본 사진에서 위의 프로그램을 돌려 얼굴을 인식해 흐림 처리한 결과입니다. 그런데... 요즘 핫한 사람의 얼굴조차 인식하지 못하고 있습니다. ^^;

face_blur_0.jpg

(첨부 파일은 이 글의 예제 코드를 포함합니다.)









[최초 등록일: ]
[최종 수정일: 4/17/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-06-16 09시16분
How to get started with neural text to speech in Azure | Azure Tips and Tricks
; https://www.youtube.com/watch?v=dl0amatX5zs&ab_channel=MicrosoftAzure
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13602정성태4/20/2024220닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024257닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024300닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024451닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024442닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024509닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024859닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024989닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241033닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241052닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241209C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241157오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241304Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241050개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241421Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241590개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241138닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241631닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...