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
정성태

... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...
NoWriterDateCnt.TitleFile(s)
585정성태6/4/200834307.NET Framework: 101. WPF - ActiveX 컨트롤 호스팅하는 방법 [2]
582정성태5/16/200826116오류 유형: 55. Windowless ActiveX controls are not supported
580정성태4/24/200825236VC++: 34. 64비트 윈도우즈에서의 이벤트 후킹
579정성태4/24/200825012VC++: 33. 변환 후의 RGS 파일 내용을 얻는 방법
577정성태4/16/200825987.NET Framework: 100. XML Serializer를 이용한 값 복사 [5]
575정성태4/7/200823188오류 유형: 54. TFS Source Control - 명령을 사용할 수 없음 [2]
574정성태3/31/200821345오류 유형: 53. TFS 연결 오류 - The workspace [...] exists on computer [...]
573정성태3/25/200825341Windows: 31. TS Web Access와 UAC [1]
570정성태3/17/200824469오류 유형: 52. TFS 연결 오류 - TF31001 [2]
569정성태3/16/200825569Team Foundation Server: 24. TFS 2008로 마이그레이션 (2) [2]
566정성태2/28/200826699.NET Framework: 99. AppDomain.GetEntryAssembly()를 우회하는 방법파일 다운로드1
564정성태2/16/200826384Windows: 30. TS Web Access + Vista SP1 [2]
563정성태2/16/200825739오류 유형: 51. Vista(UAC) + 웹 프로젝트 디버깅: System.UnauthorizedAccessException
562정성태2/12/200830001Windows: 29. Windows Server 2008 설치 [4]
561정성태1/10/200823667오류 유형: 50. IE 7 + 잘못된 HTC 파일 경로 = File not found [5]
559정성태1/1/200828479Windows: 28. Vista에서 끌어다 놓기로 GAC 등록하는 방법 [2]
558정성태1/1/200845596개발 환경 구성: 33. 32bit/64bit OLE DB Provider [1]
557정성태12/22/200723926개발 환경 구성: 32. WSCF와 VS.NET 2008
556정성태12/16/200722098기타: 22. 인기 순위 정리 : 조회수 1000 회 이상
555정성태12/16/200725033기타: 21. 인기 순위 정리 : 조회수 500 ~ 999회 글 목록
554정성태12/16/200729529기타: 20. 인기 순위 정리 : 조회수 250 ~ 499회 글 목록
553정성태12/16/200729931기타: 19. 인기 순위 정리 : 조회수 100 ~ 249회 글 목록
552정성태12/16/200723507기타: 18. 인기 순위 정리 : 조회수 000 ~ 099 회 글 목록
550정성태12/16/200722605Team Foundation Server: 23. TFS 2005에서 TFS 2008로 마이그레이션 [2]
549정성태12/16/200723975Team Foundation Server: 22. TFS 설정 - 주소를 도메인으로 변경
548정성태12/15/200741509오류 유형: 49. Report Server - 원격 서버에 연결할 수 없습니다
... 166  167  168  169  170  171  172  173  174  175  176  177  [178]  179  180  ...