0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

20行でOpenCvSharpのWebcamキャプチャ

Last updated at Posted at 2023-04-30

はじめに

C#でWebcamのキャプチャをするコンパクトなコンソールアプリを書いてみました。OpenCvSharpを使います。

前提

下記の条件が前提です。

  • Windows PCでVisual Studio Codeがインストールされている
  • C#とNugetの拡張機能がインストールされている
  • .NET Framework 4.8をターゲットにする
    Download .NET Framework 4.8.1
     (追記:.NET 7.0でも動作確認しました)

準備

  1. OpenCVのインストール
  2. プロジェクト作成
    • .NET Framework4.8の場合
      dotnet new console --target-framework-override net48 -lang c# -o webcam_console
    • .Net 7.0の場合
      dotnet new console -lang c# -o webcam_console
  3. VSCodeでwebcam_consoleフォルダを開く
  4. NugetでOpenCvSharp4.Windowsを追加

コード

Program.cs

using OpenCvSharp;
using static OpenCvSharp.Cv2;

namespace webcam_console
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var capture = new VideoCapture(0))
            using (var frame = new Mat())
            while (WaitKey(1) == -1)
            {
                capture.Read(frame);
                ImShow("Webcam: Hit any key to stop.", frame);
            }
            DestroyAllWindows();
        }
    }
}

webcam_console.csproj

  • .NET Framework4.8の場合
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net48</TargetFramework>
    </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="OpenCvSharp4.Windows" Version="4.7.0.20230115" />
  </ItemGroup>

</Project>

プロジェクトを作成後に、エラーになる行を削除する必要がありました。

  • .NET 7.0の場合
<Project Sdk="Microsoft.NET.Sdk">

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

  <ItemGroup>
    <PackageReference Include="OpenCvSharp4.Windows" Version="4.7.0.20230115" />
  </ItemGroup>

</Project>

編集の必要はありませんでした。

ビルドと実行

ターミナルで以下をタイプ:

  • dotnet build
  • dotnet run

実行環境

OS Name:                   Microsoft Windows 10 Home
OS Version:                10.0.19044 N/A Build 19044

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?