Skip to content

Commit

Permalink
Add overload of LoadImage for SkiaSharp (#230)
Browse files Browse the repository at this point in the history
  • Loading branch information
takuya-takeuchi authored May 13, 2023
1 parent fd6babe commit 8ee6bc9
Show file tree
Hide file tree
Showing 19 changed files with 395 additions and 9 deletions.
14 changes: 14 additions & 0 deletions FaceRecognitionDotNet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Shared", "tools\Shared\Shar
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FaceSearch", "examples\FaceSearch\FaceSearch.csproj", "{E12CE919-27F4-4221-AD47-E0D26B647C47}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FaceRecognitionDotNet.Extensions.Skia", "src\FaceRecognitionDotNet.Extensions.Skia\FaceRecognitionDotNet.Extensions.Skia.csproj", "{D2BBF088-62F0-49EA-9F05-5C5D207D5FE4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkiaSharpSample", "examples\SkiaSharpSample\SkiaSharpSample.csproj", "{C00A5536-B2DF-4E44-BD3A-1B7768C7AC3E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -139,6 +143,14 @@ Global
{E12CE919-27F4-4221-AD47-E0D26B647C47}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E12CE919-27F4-4221-AD47-E0D26B647C47}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E12CE919-27F4-4221-AD47-E0D26B647C47}.Release|Any CPU.Build.0 = Release|Any CPU
{D2BBF088-62F0-49EA-9F05-5C5D207D5FE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D2BBF088-62F0-49EA-9F05-5C5D207D5FE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2BBF088-62F0-49EA-9F05-5C5D207D5FE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2BBF088-62F0-49EA-9F05-5C5D207D5FE4}.Release|Any CPU.Build.0 = Release|Any CPU
{C00A5536-B2DF-4E44-BD3A-1B7768C7AC3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C00A5536-B2DF-4E44-BD3A-1B7768C7AC3E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C00A5536-B2DF-4E44-BD3A-1B7768C7AC3E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C00A5536-B2DF-4E44-BD3A-1B7768C7AC3E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -165,6 +177,8 @@ Global
{2462DBBC-3902-4C92-B1D3-F1CB09AE0995} = {8C8838E0-B002-426F-9B25-4C1F65A6D33D}
{91B27982-5175-48B6-B653-6F5F022F488C} = {8C8838E0-B002-426F-9B25-4C1F65A6D33D}
{E12CE919-27F4-4221-AD47-E0D26B647C47} = {FEEAC07F-70D7-4C12-B92C-153CEE0F2539}
{D2BBF088-62F0-49EA-9F05-5C5D207D5FE4} = {2F845E5F-E6B9-46D5-B5D8-52BEE4B463F0}
{C00A5536-B2DF-4E44-BD3A-1B7768C7AC3E} = {FEEAC07F-70D7-4C12-B92C-153CEE0F2539}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4D44C572-D749-4A76-A199-8C598A08AE8A}
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ This package supports cross platform, Windows, Linux and MacOSX!!

##### :warning: FaceRecognitionDotNet for ARM is not tested yet

### Extensions package

|Package|Nuget|
|---|---|
|FaceRecognitionDotNet.Extensions.Skia|[![NuGet version](https://img.shields.io/nuget/v/FaceRecognitionDotNet.Extensions.Skia.svg)](https://www.nuget.org/packages/FaceRecognitionDotNet)|

## Support API

|face_recognition API|Corresponding API|Note|
Expand Down
4 changes: 4 additions & 0 deletions examples/SkiaSharpSample/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dlib_face_recognition_resnet_model_v1.dat
mmod_human_face_detector.dat
shape_predictor_5_face_landmarks.dat
shape_predictor_68_face_landmarks.dat
90 changes: 90 additions & 0 deletions examples/SkiaSharpSample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.IO;
using System.Linq;
using System.Net.Http;

using FaceRecognitionDotNet;
using Microsoft.Extensions.CommandLineUtils;
using SkiaSharp;

namespace SkiaSharpSample
{

internal class Program
{

#region Fields

private static FaceRecognition _FaceRecognition;

#endregion

#region Methods

private static void Main(string[] args)
{
var app = new CommandLineApplication(false);
app.Name = nameof(SkiaSharpSample);
app.Description = "The program for measure face encoding performance";
app.HelpOption("-h|--help");

var modelsOption = app.Option("-m|--model", "model files directory path", CommandOptionType.SingleValue);

app.OnExecute(() =>
{
if (!modelsOption.HasValue())
{
app.ShowHelp();
return -1;
}
var directory = modelsOption.Value();
if (!Directory.Exists(directory))
{
app.ShowHelp();
return -1;
}
_FaceRecognition = FaceRecognition.Create(directory);
var testImages = new[]
{
"obama-240p.jpg",
"obama-480p.jpg",
"obama-720p.jpg",
"obama-1080p.jpg"
};
const string url = "https://upload.wikimedia.org/wikipedia/commons/9/9d/Barack_Obama.jpg";
var binary = new HttpClient().GetByteArrayAsync(url).Result;
using (var bitmap = SKBitmap.Decode(binary))
using (var searchImage = FaceRecognitionDotNet.Extensions.Skia.FaceRecognition.LoadImage(bitmap))
{
var searchEncodings = _FaceRecognition.FaceEncodings(searchImage);
foreach (var path in testImages)
{
var targetImage = FaceRecognition.LoadImageFile(path);
var targetEncoding = _FaceRecognition.FaceEncodings(targetImage);
var distance = FaceRecognition.FaceDistance(searchEncodings.First(), targetEncoding.First());
Console.WriteLine($"Distance: {distance} for {path}");
foreach (var encoding in targetEncoding) encoding.Dispose();
}
foreach (var encoding in searchEncodings) encoding.Dispose();
}
return 0;
});

app.Execute(args);
}

#endregion

}

}
43 changes: 43 additions & 0 deletions examples/SkiaSharpSample/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# SkiaSharpSharp Sample

This sample requires to use CUDA.

## How to use?

## 1. Preparation

This sample requires model files.

## 2. Build

1. Open command prompt and change to <SkiaSharpSharpSample_dir>
1. Type the following command
````
$ dotnet remove reference ../../src/FaceRecognitionDotNet\FaceRecognitionDotNet.csproj
$ dotnet remove reference ../../src/FaceRecognitionDotNet\FaceRecognitionDotNet.Extensions.Skia.csproj
$ dotnet add package FaceRecognitionDotNet
$ dotnet add package FaceRecognitionDotNet.Extensions.Skia
$ dotnet build -c Release
````

## 3. Run

1. Open command prompt and change to <SkiaSharpSharpSample_dir>
1. Type the following sample command
````
$ dotnet run -c Release -- "-m=models"
Distance: 0.342289226629347 for obama-240p.jpg
Distance: 0.346749102653167 for obama-480p.jpg
Distance: 0.369195738248585 for obama-720p.jpg
Distance: 0.361052041208253 for obama-1080p.jpg
````

## 4. Parameters

This program support the following argument and option.

### Argument

|Argument|Description|
|:---|:---|
|-m\|--model|Directory path includes model files|
17 changes: 17 additions & 0 deletions examples/SkiaSharpSample/SkiaSharpSample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<Authors>Takuya Takeuchi</Authors>
<Description>Example of FaceRecognitionDotNet</Description>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FaceRecognitionDotNet" Version="1.3.0.8" />
<PackageReference Include="FaceRecognitionDotNet.Extensions.Skia" Version="1.3.0.8" />
<PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" />
<PackageReference Include="SkiaSharp" Version="2.88.3" />
</ItemGroup>

</Project>
Binary file added examples/SkiaSharpSample/obama-1080p.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/SkiaSharpSample/obama-240p.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/SkiaSharpSample/obama-480p.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/SkiaSharpSample/obama-720p.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 8 additions & 0 deletions licenses/SkiaSharp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Copyright (c) 2015-2016 Xamarin, Inc.
Copyright (c) 2017-2018 Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 changes: 6 additions & 0 deletions nuget/CreateAllPackage.ps1
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
$targets = @(
"Extensions.Skia",
"CPU",
"CUDA92",
"CUDA100",
Expand All @@ -18,6 +19,11 @@ $source = Join-Path $FaceRecognitionDotNetRoot src | `
dotnet restore ${source}
dotnet build -c Release ${source}

$source = Join-Path $FaceRecognitionDotNetRoot src | `
Join-Path -ChildPath FaceRecognitionDotNet.Extensions.Skia
dotnet restore ${source}
dotnet build -c Release ${source}

foreach ($target in $targets)
{
pwsh CreatePackage.ps1 $target
Expand Down
7 changes: 0 additions & 7 deletions nuget/ExtractNupkgToArtifacts.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,6 @@ $PublishTargets = @{ "FaceRecognitionDotNet"="cpu";
"FaceRecognitionDotNet.MKL"="mkl";
}

$Token = $env:FaceRecognitionDotNetNugetToken
if ([string]::IsNullOrWhitespace($Token))
{
Write-Host "nuget token is missing" -ForegroundColor Red
exit
}

# Precheck whether all package is present
foreach ($key in $PublishTargets.keys)
{
Expand Down
131 changes: 131 additions & 0 deletions src/FaceRecognitionDotNet.Extensions.Skia/FaceRecognition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using System;
using System.Runtime.InteropServices;

using DlibDotNet;
using SkiaSharp;

namespace FaceRecognitionDotNet.Extensions.Skia
{

public sealed class FaceRecognition
{

#region Methods

/// <summary>
/// Creates an <see cref="Image"/> from the specified existing bitmap image.
/// </summary>
/// <param name="bitmap">The <see cref="SKBitmap"/> from which to create the new <see cref="Image"/>.</param>
/// <returns>The <see cref="Image"/> this method creates.</returns>
/// <exception cref="ArgumentNullException"><paramref name="bitmap"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">The specified <see cref="SKColorType"/> is not supported.</exception>
public static Image LoadImage(SKBitmap bitmap)
{
var width = bitmap.Width;
var height = bitmap.Height;
var colorType = bitmap.ColorType;

Mode mode;
int srcChannel;
int dstChannel;
switch (colorType)
{
case SKColorType.Rgba8888:
mode = Mode.Rgb;
srcChannel = 4;
dstChannel = 3;
break;
case SKColorType.Bgra8888:
mode = Mode.Rgb;
srcChannel = 4;
dstChannel = 3;
break;
case SKColorType.Gray8:
mode = Mode.Greyscale;
srcChannel = 1;
dstChannel = 1;
break;
default:
throw new ArgumentOutOfRangeException($"{nameof(bitmap)}", $"The specified {nameof(SKColorType)} is not supported.");
}

unsafe
{
var array = new byte[width * height * dstChannel];
fixed (byte* pArray = &array[0])
{

switch (srcChannel)
{
case 1:
{
var src = bitmap.GetPixels();
var stride = bitmap.RowBytes;

for (var h = 0; h < height; h++)
Marshal.Copy(IntPtr.Add(src, h * stride), array, h * width, width * dstChannel);
}
break;
case 3:
case 4:
{
if (colorType == SKColorType.Rgba8888)
{
var src = (byte*)bitmap.GetPixels();
var stride = bitmap.RowBytes;

for (var h = 0; h < height; h++)
{
var srcOffset = h * stride;
var dstOffset = h * width * dstChannel;

for (var w = 0; w < width; w++)
{
pArray[dstOffset + w * dstChannel + 0] = src[srcOffset + w * srcChannel + 0];
pArray[dstOffset + w * dstChannel + 1] = src[srcOffset + w * srcChannel + 1];
pArray[dstOffset + w * dstChannel + 2] = src[srcOffset + w * srcChannel + 2];
}
}
}
else
{
var src = (byte*)bitmap.GetPixels();
var stride = bitmap.RowBytes;

for (var h = 0; h < height; h++)
{
var srcOffset = h * stride;
var dstOffset = h * width * dstChannel;

for (var w = 0; w < width; w++)
{
// BGR order to RGB order
pArray[dstOffset + w * dstChannel + 0] = src[srcOffset + w * srcChannel + 2];
pArray[dstOffset + w * dstChannel + 1] = src[srcOffset + w * srcChannel + 1];
pArray[dstOffset + w * dstChannel + 2] = src[srcOffset + w * srcChannel + 0];
}
}
}
}
break;
}

var ptr = (IntPtr)pArray;
switch (mode)
{
case Mode.Rgb:
return new Image(new Matrix<RgbPixel>(ptr, height, width, width * 3), Mode.Rgb);
case Mode.Greyscale:
return new Image(new Matrix<byte>(ptr, height, width, width), Mode.Greyscale);
}
}
}

return null;
}

#endregion

}

}
Loading

0 comments on commit 8ee6bc9

Please sign in to comment.