顔ぼかしの自動化:AWS と .NET でプライバシーを保護
AWS Rekognition で顔の位置を検出し、C# と Magick.NET で該当領域をローカルでぼかします。このコンソールアプリケーションは、共有前に確認するための新しい PNG を作成します。顔の検出には見落としがあり、ぼかしによって匿名性が保証されるわけではありません。許可を得た写真だけを AWS に送信し、結果に識別可能な顔やその他の個人を特定できる情報がないか確認してください。
.NET プロジェクトのセットアップ
以下のコマンドは Linux 上の Bash と .NET 10 SDK を使用します。テストに使用した SDK は 10.0.111 です。新規開発には、保守更新が適用された .NET 10 SDK を使用してください。ランタイムだけでなく SDK をインストールし、開始前に dotnet --version が動作することを確認してください。Magick.NET の NuGet パッケージにはネイティブ画像ライブラリが含まれているため、このアプリケーションに別途 ImageMagick 実行ファイルを用意する必要はありません。
既存の .NET ソースツリーの外にある、書き込み可能なディレクトリで作業を始めてください。この小さなプロジェクトが無関係な設定を継承しないよう、セットアップは上位ディレクトリにビルド、パッケージ、SDK、NuGet の構成がある場合に実行を拒否します。次のブロックを貼り付けてください。丸括弧により、シェルのディレクトリとオプションは変更されません。
(
set -eu
command -v dotnet >/dev/null || { printf '%s\n' 'Install the .NET 10 SDK first.' >&2; exit 1; }
parent=$PWD
while :; do
for config in global.json Directory.Build.props Directory.Build.targets Directory.Packages.props NuGet.Config NuGet.config nuget.config; do
[ ! -e "$parent/$config" ] || { printf '%s\n' 'Use a directory outside an existing .NET configuration tree.' >&2; exit 1; }
done
[ "$parent" -ef / ] && break
parent="$parent/.."
done
[ ! -e FaceBlurAutomation ] || { printf '%s\n' 'Choose a new project directory; FaceBlurAutomation already exists.' >&2; exit 1; }
dotnet new console --framework net10.0 --no-restore -n FaceBlurAutomation
dotnet add FaceBlurAutomation package AWSSDK.Rekognition --version 4.0.101.2
dotnet add FaceBlurAutomation package Magick.NET-Q8-AnyCPU --version 14.17.2
)
プロジェクト作成後にインストールが失敗した場合は、そのディレクトリを残し、接続が復旧してから二つのパッケージコマンドを再実行してください。セットアップ全体では、意図的に既存プロジェクトの再利用を拒否します。以降のコマンドはすべて、元のディレクトリから --project を使って実行します。
このローカルでの手順では、既存の共有認証情報プロファイル、または環境変数で渡す一時認証情報を使用します。SDK のデフォルト認証情報プロバイダーチェーンを通じて設定してください。使用する ID には rekognition:DetectFaces が必要です。必要に応じて Bash セッションで AWS_PROFILE に共有認証情報プロファイル名を設定し、export してください。Bash セッションで AWS_REGION に
us-east-1 などの Rekognition リージョンを設定して export してください。コードにキーを貼り付けないでください。Rekognition による分析には AWS の料金が発生します。この例では画像のバイト列を直接送信するため、S3 バケットも S3 の権限も必要ありません。
AWS Rekognition の概要
DetectFaces は、大きい順に最大 100 個の顔のバウンディングボックスを返します。各座標は、画像の幅または高さに対する割合です。端にある顔の座標は画像の範囲外になることがあるため、コードでは外側に丸めてから矩形を画像の範囲内に収めます。正面を向いた顔で最もよく機能します。空のレスポンスは手動確認が必要な理由であり、画像に人がいない証拠ではありません。
顔検出とぼかしの実装
8 ビットの RGB またはグレースケールのピクセルで構成された、単一画像の JPEG または PNG を使用してください。PNG にアルファチャンネルがあってはいけません。この例では CMYK、アルファチャンネル(完全に不透明なものを含む)、より高いビット深度、アニメーション PNG、複数画像の JPEG を拒否します。事前に画像エディターで、画像を一枚のアルファなし 8 ビット sRGB PNG として書き出してください。ローカル入力の上限は 20 MiB、デコード後のピクセル数は 20 メガピクセルで、縦横ともに最低 80 ピクセルが必要です。これらは信頼できるローカル写真を対象としたチュートリアル用の制限であり、悪意のあるアップロードに対応するサンドボックスではありません。
アプリケーションはピクセルの向きを補正し、プロファイル付きの RGB カラーを sRGB に変換して、入力のプロファイルとコメントを削除し、最長辺が 1,600 ピクセルを超える写真を縮小します。その同じピクセルを PNG として AWS に送信し、その作業用画像を編集します。そのため、大きな写真からは小さな出力が生成されます。小さくなった顔を注意深く確認してください。正規化した PNG がなお直接 Bytes 送信の上限である 5 MBを超える場合は、より小さな写真を書き出して再試行するようエラーで案内されます。別途定められている S3 オブジェクトの上限 15 MB は、ここでは適用されません。
FaceBlurAutomation/Program.cs を次のプログラム全体で置き換えてください。
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Rekognition;
using Amazon.Rekognition.Model;
using ImageMagick;
namespace FaceBlurAutomation;
public static class Program
{
public static async Task<int> Main(string[] args)
{
try
{
if (args.Length != 2)
throw new ArgumentException("Usage: FaceBlurAutomation <inputImagePath> <newOutput.png>");
return await ProcessImageAsync(args[0], args[1]);
}
catch (Exception error)
{
string message = error switch
{
ArgumentException or InvalidDataException => error.Message,
OperationCanceledException => "AWS analysis timed out after 45 seconds. Check connectivity and retry with a new output path.",
AmazonRekognitionException => "AWS analysis failed. Check your profile, region, DetectFaces permission, and service availability.",
Amazon.Runtime.AmazonClientException => "AWS credentials or client setup failed. Check your shared-credentials profile and AWS_REGION.",
System.Net.Http.HttpRequestException => "AWS connectivity failed. Check your network and region before retrying.",
MagickException => "Image decoding or processing failed. Re-export an intact 8-bit RGB PNG and retry.",
IOException or UnauthorizedAccessException => "File access or publication failed. Check the input, output directory, and existing destination.",
_ => "Processing failed; no successful result was reported."
};
Console.Error.WriteLine(message);
return 1;
}
}
private static async Task<int> ProcessImageAsync(string inputPath, string outputPath)
{
outputPath = Path.GetFullPath(outputPath);
if (!string.Equals(Path.GetExtension(outputPath), ".png", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("Choose a .png output path.");
if (File.Exists(outputPath) || Directory.Exists(outputPath))
throw new ArgumentException("Choose an output path that does not already exist.");
if (!Directory.Exists(Path.GetDirectoryName(outputPath)))
throw new ArgumentException("Create the output directory first.");
using var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.Read);
if (input.Length == 0 || input.Length > 20L * 1024 * 1024)
throw new InvalidDataException("Use a nonempty input no larger than 20 MiB; export a smaller image and retry.");
if (HasMultiplePictureIndex(input))
throw new InvalidDataException("This JPEG contains a multi-picture index. Export one picture as an opaque 8-bit RGB PNG first.");
if (HasPngAnimation(input))
throw new InvalidDataException("This PNG contains animation controls. Export one frame as an 8-bit RGB PNG without alpha first.");
using var headers = new MagickImageCollection();
headers.Ping(input);
if (headers.Count != 1)
throw new InvalidDataException("Export a single image as an opaque 8-bit RGB PNG first.");
var header = headers[0];
if (header.Format is not (MagickFormat.Jpeg or MagickFormat.Png)
|| header.Depth != 8 || header.HasAlpha
|| header.ColorSpace is not (ColorSpace.sRGB or ColorSpace.Gray))
throw new InvalidDataException("Use an 8-bit RGB or grayscale JPEG, or a PNG without an alpha channel; convert CMYK or alpha in an image editor first.");
if (header.Width < 80 || header.Height < 80
|| (ulong)header.Width * header.Height > 20_000_000)
throw new InvalidDataException("Use sides of at least 80 pixels and no more than 20 million pixels; resize in your image editor first.");
input.Position = 0;
using var image = new MagickImage();
image.Warning += (_, _) => throw new InvalidDataException("The decoder reported damaged image data. Re-export an intact image first.");
image.Read(input);
image.AutoOrient();
if (image.GetColorProfile() is not null)
image.TransformColorSpace(ColorProfiles.SRGB);
image.ColorSpace = ColorSpace.sRGB;
image.Strip();
if (image.Width > 1600 || image.Height > 1600)
image.Resize(new MagickGeometry(1600, 1600) { Greater = true });
if (image.Width < 80 || image.Height < 80)
throw new InvalidDataException("The resized image has a side below 80 pixels; crop the extreme aspect ratio first.");
using var bytes = new MemoryStream(image.ToByteArray(MagickFormat.Png));
if (bytes.Length > 5L * 1024 * 1024)
throw new InvalidDataException("The normalized PNG exceeds AWS’s 5 MB Bytes limit. Export with a longest side of 1200 pixels or less and retry.");
using var client = new AmazonRekognitionClient(new AmazonRekognitionConfig { MaxErrorRetry = 0 });
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(45));
var response = await client.DetectFacesAsync(new DetectFacesRequest
{
Image = new Amazon.Rekognition.Model.Image { Bytes = bytes },
Attributes = new List<string> { "DEFAULT" }
}, deadline.Token);
var faces = response.FaceDetails ?? new List<FaceDetail>();
if (faces.Count == 0)
{
Console.Error.WriteLine("No faces detected; no output written. Review the original manually.");
return 2;
}
foreach (var face in faces)
{
var box = face.BoundingBox;
if (box?.Left is not float left || box.Top is not float top
|| box.Width is not float width || box.Height is not float height
|| !float.IsFinite(left) || !float.IsFinite(top)
|| !float.IsFinite(width) || !float.IsFinite(height) || width <= 0 || height <= 0)
throw new InvalidDataException("AWS returned an invalid face bounding box; no output written.");
int x1 = (int)Math.Floor(Math.Clamp((double)left * image.Width, 0, image.Width));
int y1 = (int)Math.Floor(Math.Clamp((double)top * image.Height, 0, image.Height));
int x2 = (int)Math.Ceiling(Math.Clamp(((double)left + width) * image.Width, 0, image.Width));
int y2 = (int)Math.Ceiling(Math.Clamp(((double)top + height) * image.Height, 0, image.Height));
if (x2 <= x1 || y2 <= y1)
throw new InvalidDataException("A face box does not intersect the image; no output written.");
using var region = image.Clone();
region.Crop(new MagickGeometry(x1, y1, (uint)(x2 - x1), (uint)(y2 - y1)));
region.ResetPage();
double sigma = Math.Max(12, Math.Min(region.Width, region.Height) / 4.0);
// An explicit kernel radius keeps large-sigma blur effective with the Q8 library.
region.GaussianBlur(Math.Ceiling(3 * sigma), sigma);
image.Composite(region, x1, y1, CompositeOperator.Copy);
}
string staging = Path.Combine(Path.GetDirectoryName(outputPath)!,
$".faceblur-{Guid.NewGuid():N}.tmp");
try
{
using (var output = new FileStream(staging, FileMode.CreateNew, FileAccess.Write))
{
image.Write(output, MagickFormat.Png);
output.Flush(flushToDisk: true);
}
File.Move(staging, outputPath, overwrite: false);
}
finally
{
if (File.Exists(staging)) File.Delete(staging);
}
Console.WriteLine($"Blurred {faces.Count} detected face region(s). Review {outputPath} before sharing.");
return 0;
}
private static bool HasPngAnimation(Stream input)
{
// PNG decoders can expose only an APNG's default image; inspect its control chunks first.
try
{
Span<byte> header = stackalloc byte[8];
ReadOnlySpan<byte> signature = stackalloc byte[] { 137, 80, 78, 71, 13, 10, 26, 10 };
if (input.Read(header) != 8 || !header.SequenceEqual(signature)) return false;
while (input.Length - input.Position >= 12)
{
input.ReadExactly(header);
uint length = BinaryPrimitives.ReadUInt32BigEndian(header[..4]);
if ((long)length + 4 > input.Length - input.Position) break;
if (header[4..].SequenceEqual("acTL"u8)) return true;
// A valid animation control chunk must precede the first image-data chunk.
if (header[4..].SequenceEqual("IDAT"u8) || header[4..].SequenceEqual("IEND"u8)) break;
input.Position += length + 4L;
}
return false;
}
finally
{
input.Position = 0;
}
}
private static bool HasMultiplePictureIndex(Stream input)
{
// Some JPEG decoders expose only the primary picture of an MPF/MPO file.
try
{
if (input.ReadByte() != 0xff || input.ReadByte() != 0xd8) return false;
while (input.Position < input.Length)
{
if (input.ReadByte() != 0xff) break;
int marker;
do { marker = input.ReadByte(); } while (marker == 0xff);
if (marker < 0 || marker == 0xda || marker == 0xd9) break;
if (marker == 0x01 || marker is >= 0xd0 and <= 0xd7) continue;
int high = input.ReadByte();
int low = input.ReadByte();
if (high < 0 || low < 0) break;
int length = (high << 8) + low - 2;
if (length < 0 || length > input.Length - input.Position) break;
long next = input.Position + length;
if (marker == 0xe2 && length >= 4
&& input.ReadByte() == 'M' && input.ReadByte() == 'P'
&& input.ReadByte() == 'F' && input.ReadByte() == 0)
return true;
input.Position = next;
}
return false;
}
finally
{
input.Position = 0;
}
}
}
分析の許可を得ている写真を、元のディレクトリに input.jpg として保存してください。新しい保存先を選び、ビルドして実行します。
dotnet build FaceBlurAutomation &&
dotnet run --no-build --project FaceBlurAutomation -- "./input.jpg" "./output.png"
実行が完了すると、ぼかした領域の数が報告され、output.png の確認を求められます。そのファイルを画像ビューアーで開き、元の画像と比較してください。見えているすべての顔、回転、画像サイズ、ぼかしの強さが十分かどうかを確認します。髪、衣服、周囲の状況、または検出器が見落とした顔から、人物が特定される可能性は残ります。再実行には新しい出力名を使用してください。プログラムは既存のファイルを保持します。
動作の仕組み
向きの補正とサイズ変更は検出前に行うため、返される座標は編集中のピクセルに対応します。範囲内に収めた各矩形を切り出し、ぼかしてから元の位置にコピーします。それらの矩形の和集合の外にあるピクセルは、正規化した作業用画像のまま変わりません。シグマは最低 12 ピクセルで、各顔のボックスの短辺に応じて大きくなります。Q8 パッケージでもぼかしが十分に効くよう、カーネル半径を明示的に設定しています。これにより顔のサイズが異なっても強い効果が得られますが、この設定は匿名性を判断するしきい値ではありません。
PNG はまず、保存先と同じディレクトリに一意の名前を持つステージングファイルとしてエンコードされます。ファイルを閉じた後、上書きしない移動操作で最終ファイルとして配置します。書き込みや移動の失敗を捕捉した場合はステージングファイルを削除しますが、プロセスの強制終了や電源断が起きると .faceblur-*.tmp ファイルが残ることがあります。中断した実行に属する一時ファイルだけを確認して削除してください。このローカルの例は、一度に一回だけ実行することを想定しています。
エラー処理とテスト
終了コード 0 は、PNG が最終ファイルとして配置され、まだ確認が必要であることを示します。終了コード 2 は、顔が検出されず、出力が書き込まれなかったことを示します。終了コード 1 は、不正な入力、AWS の失敗、ファイル処理または最終ファイル配置の失敗を表します。AWS の例外本文や認証情報は出力しません。
複数の顔が写った写真と、顔が写っていない写真を試してください。EXIF による回転情報付き JPEG、既存の保存先、破損画像、利用できない出力ディレクトリもテストします。処理が拒否された場合、新しい最終ファイルは作成されず、入力は保持されるはずです。バイト数やピクセル数の制限に達した場合は、ローカルでサイズを変更して書き出してください。色や形式が理由で拒否された場合は、画像を一枚のアルファなし 8 ビット sRGB PNG として書き出してください。タイムアウトは AWS リクエストに適用されるもので、画像処理全体に適用されるものではありません。再試行する前に接続を確認してください。この例では SDK の再試行を無効にしています。
アプリケーションの拡張
Web API には、独自のアップロード検証、リソース制限、認可、非公開の一時ストレージが必要です。上記の信頼できるファイル向けの例には、これらの制御は含まれていません。S3 入力パスを使う場合は S3 へのアクセスも必要で、オブジェクトは Rekognition と同じリージョンになければなりません。ストレージを追加する場合も、ある版の画像を検出して別の版を編集するのではなく、向きとサイズを補正した同じ画像に対して検出とぼかしを行ってください。
まとめ
PNG を確認し、見落とされた顔を手動で処理し終えるまで、元の写真を保持してください。その他の AWS 画像分析タスクには、Transloadit の 🤖 /image/describe Robot がオブジェクトのラベルを返します。ただし、ここで紹介した顔のぼかしや確認の手順に代わるものではありません。
