OpenCVSharpで高さ基準で画像ファイルをリサイズするコンソールアプリ

コンピュータ

画像ファイルの高さを揃えたい。

ソースコード

ファイル名:ResizeH.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;

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 < 2)
        {
            Console.Error.WriteLine(
                "Usage: resizeheight <input> <output> [height]");
            return ARG_ERROR;
        }

        string inputPath = args[0];
        string outputPath = args[1];

        int targetHeight = -1;
        if (args.Length >= 3 && int.TryParse(args[2], out int h))
        {
            targetHeight = h;
        }

        try
        {
            using var src = Cv2.ImRead(inputPath, ImreadModes.Unchanged);

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

            // 高さ未指定なら元画像の高さ
            if (targetHeight <= 0)
                targetHeight = src.Height;

            double scale = (double)targetHeight / src.Height;
            int targetWidth = (int)(src.Width * scale);

            using var dst = new Mat();
            Cv2.Resize(
                src,
                dst,
                new Size(targetWidth, targetHeight),
                0,
                0,
                InterpolationFlags.Area
            );

            Cv2.ImWrite(outputPath, dst);
            return OK;
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.ToString());
            return PROCESS_ERROR;
        }
    }
}
/*
ビルド
dotnet build -c Release -o インストール先のフォルダのパス

実行例
.\resizeheight.exe in.png out.png 720
*/

コメント