Search code examples
c#webcam.net-5

capture images from webcam using c# with .net5


I am trying to make a simple form to capture images from webCam, on my .net5 project however I could not seem to find a simple solution for this. I try AForge, OpenCVSharp.. they do not support .net5 yet I got a project to run but it turns out just blank (no webcam image). I google search and try almost everything I can found on my end.

I am wondering if anyone got any suggestions for a solution to this problem prefer opensource components

edit1: I am using Winforms for desktop applications.


Solution

  • OpenCvSharp4 supports .NET5 (and also .NET6 preview :-)).

    How to reproduce

    1. Create an empty "Windows Forms App" project form Visual Studio. (Obviously don't use .NET Framework...)

    2. Add nuget package OpenCvSharp4.Windows. Below my csproj file.

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net5.0-windows7.0</TargetFramework>
        <Nullable>enable</Nullable>
        <UseWindowsForms>true</UseWindowsForms>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="OpenCvSharp4.Windows" Version="4.5.3.20210817" />
      </ItemGroup>
    
    </Project>
    
    1. Add a Button and a PictureBox to Form1 using designer.

    2. Copy and paste code below in the Form1.cs.

    using OpenCvSharp;
    using OpenCvSharp.Extensions;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WebCam
    {
        public partial class Form1 : Form
        {
            VideoCapture capture;
            Mat frame;
            Bitmap image;
    
            public Form1()
            {
                InitializeComponent();
    
                frame = new Mat();
                capture = new VideoCapture(0);
                capture.Open(0);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
    
                if (capture.IsOpened())
                {
                    capture.Read(frame);
                    image = BitmapConverter.ToBitmap(frame);
                    if (pictureBox1.Image != null)
                    {
                        pictureBox1.Image.Dispose();
                    }
                    pictureBox1.Image = image;
                }
            }
        }
    }
    
    

    That's all.