OpenCVSharpで画像ファイルの解像度情報を取得するコンソールアプリ

コンピュータ

画像ファイルから、幅、高さ、チャンネル数、種類をJSON形式で出力するコマンド

ソースコード

ファイル名:imginfo.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
    <PackageReference Include="OpenCvSharp4.runtime.win" Version="4.11.0.20250507" />
  </ItemGroup>

</Project>

ファイル名:Program.cs

using System;
using OpenCvSharp;
using System.Text.Json;

class Program
{
    static int Main(string[] args)
    {
        const int OK = 0;
        const int ARG_ERROR = 1;
        const int IO_ERROR = 2;
        const int PROCESS_ERROR = 3;

        if (args.Length < 1)
        {
            Console.Error.WriteLine("Usage: imginfo <imagePath>");
            return ARG_ERROR;
        }

        string path = args[0];

        try
        {
            Console.Error.WriteLine($"Loading: {path}");

            using var mat = Cv2.ImRead(path, ImreadModes.Unchanged);

            if (mat.Empty())
            {
                Console.Error.WriteLine("Failed to load image.");
                return IO_ERROR;
            }

            var info = new
            {
                Width = mat.Width,
                Height = mat.Height,
                Channels = mat.Channels(),
                Type = mat.Type().ToString()
            };

            // JSON を stdout に出力
            var json = JsonSerializer.Serialize(
                info,
                new JsonSerializerOptions
                {
                    WriteIndented = true
                });

            Console.WriteLine(json);
            return OK;
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.ToString());
            return PROCESS_ERROR;
        }
    }
}

/*
ビルド方法
dotnet build -c Release -o インストール先のフォルダのパス

PowerShell使い方
$info = .\imginfo.exe test.png | ConvertFrom-Json

$info.Width
$info.Height
$info.Channels
$info.Type

エラーハンドリング込み例
$info = .\imginfo.exe test.png 2> err.log

if ($LASTEXITCODE -ne 0) {
    throw "imginfo failed (code=$LASTEXITCODE)"
}

$info = $info | ConvertFrom-Json
*/

実行例

PS J:\csharp\console\imginfo> imginfo a01.png
Loading: a01.png
{
  "Width": 800,
  "Height": 1140,
  "Channels": 4,
  "Type": "CV_8UC4"
}

コメント