C#で画像ファイルをグレイスケール化するCLIコマンド

C# コンピュータ
C#

コマンドラインで画像ファイルをグレイスケールに変換します。

プロジェクトの作成

mkdir ToGray
cd ToGray
dotnet new console
dotnet add package System.CommandLine --prerelease
dotnet add package OpenCvSharp4
dotnet add package OpenCvSharp4.Windows
dotnet add package OpenCvSharp4.Extensions

ソースコード

using System.CommandLine;
using OpenCvSharp;

namespace ToGray;
class Program
{
    static readonly string AppName = "ToGray";
    static void Filter(FileInfo file, string dir)
    {
        if (!File.Exists(file.FullName)) return;
        if (dir == "")
        {
            dir = Path.Join(file.DirectoryName ?? ".", AppName);
        }
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        var mat = Cv2.ImRead(file.FullName, ImreadModes.Grayscale);
        string outFile = Path.Join(dir, file.Name);
        Cv2.ImWrite(outFile, mat);
        Console.WriteLine($"{outFile}");
    }
    static async Task<int> Main(string[] args)
    {
        var fileOption = new Option<FileInfo?>(
            name: "--file",
            description: "入力画像ファイル"
        ){ IsRequired = true };
        var dirOption = new Option<string>(
            name: "--dir",
            description: "出力先のディレクトリ",
            getDefaultValue: () => ""
        ){ IsRequired = true };
        var rootCommand = new RootCommand(
            "画像ファイルをグレースケール化"
        );
        rootCommand.AddOption(fileOption);
        rootCommand.AddOption(dirOption);

        rootCommand.SetHandler((file, comment) => 
            {
                Filter(file!, comment);
            },
            fileOption, dirOption);

        return await rootCommand.InvokeAsync(args);
    }
}
Download

コメント