🔥 Programming/OpenCV

[OpenCV4] C# OpenCV4 WebCam 사용하기

스쳐가는비 2022. 9. 23. 13:59

C# OpenCV4

Webcam 사용하기

 

OpenCv4를 사용하기에, 기본적으로 OpenCV4 Nuget 추가를 해주셔야합니다.

Code

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;
using System.Threading.Tasks;
using System.Windows.Forms;
using Point = OpenCvSharp.Point;

namespace WebCam
{
    public partial class Form1 : Form
    {
        Task refresh;
        VideoCapture _capture;

        public Form1()
        {
            InitializeComponent();

            _capture = new VideoCapture();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _capture.Open(0, VideoCaptureAPIs.ANY);
            if (!_capture.IsOpened())
            {
                Close();
                return;
            }

            ClientSize = new System.Drawing.Size(_capture.FrameWidth, _capture.FrameHeight);
            refresh = Task.Run(() => RefreshFuc());
        }

        private void RefreshFuc()
        {
            try
            {
                while (true)
                {
                    using (var VideoMat = _capture.RetrieveMat())
                    {
                        using (var OldImg = pictureBox1.Image)
                        {
                            pictureBox1.Image = VideoMat.ToBitmap();
                        }

                    }
                    Thread.Sleep(10);
                }
            }
            catch(Exception ex)
            {

            }
        }
    }
}

 

Result