728x90
반응형

1. 목적

  • WPF에서 OpenCV를 활용하여 기본 WPF 컨트롤인 Image에 노트북 (또는 USB) 카메라에서 가져온 영상을 Bitmap 형식으로 그려줌
  • 환경 구축 및 빌드는 https://hwan001.tistory.com/144?category=836235 링크 참조

 

2. 코드 (Xaml)

<Window x:Class="WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF"
        Loaded="windows_loaded"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="600">
    <Grid>
        <Image Name="Cam_1" Margin="20,20,20,100"/>
    </Grid>
</Window>

 

3. 코드 (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

// OpenCV 사용을 위한 using
using OpenCvSharp;
using OpenCvSharp.WpfExtensions;

// Timer 사용을 위한 using
using System.Windows.Threading;

namespace WPF
{
    // OpenCvSharp 설치 시 Window를 명시적으로 사용해 주어야 함 (window -> System.Windows.Window)
    public partial class MainWindow : System.Windows.Window
    {
    	// 필요한 변수 선언
        VideoCapture cam;
        Mat frame;
        DispatcherTimer timer;
        bool is_initCam, is_initTimer;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void windows_loaded(object sender, RoutedEventArgs e)
        {
            // 카메라, 타이머(0.01ms 간격) 초기화
            is_initCam = init_camera();
            is_initTimer = init_Timer(0.01); 

            // 초기화 완료면 타이머 실행
            if(is_initTimer && is_initCam) timer.Start();
        }

        private bool init_Timer(double interval_ms)
        {
            try
            {
                timer = new DispatcherTimer();

                timer.Interval = TimeSpan.FromMilliseconds(interval_ms);
                timer.Tick += new EventHandler(timer_tick);

                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool init_camera() {
            try {
                // 0번 카메라로 VideoCapture 생성 (카메라가 없으면 안됨)
                cam = new VideoCapture(0);
                cam.FrameHeight = (int)Cam_1.Height;
                cam.FrameWidth = (int)Cam_1.Width;

                // 카메라 영상을 담을 Mat 변수 생성
                frame = new Mat();

                return true;
            }catch{
                return false;
            }
        }

        private void timer_tick(object sender, EventArgs e)
        {
            // 0번 장비로 생성된 VideoCapture 객체에서 frame을 읽어옴
            cam.Read(frame);
            // 읽어온 Mat 데이터를 Bitmap 데이터로 변경 후 컨트롤에 그려줌
            Cam_1.Source = OpenCvSharp.WpfExtensions.WriteableBitmapConverter.ToWriteableBitmap(frame);
        }
    }
}

 

 

4. 결과

결과

728x90
반응형
728x90
반응형

1. 설치 목적

  • WPF에서 OpenCV 최신 버전(2022년 2월 2일 기준) 기능 사용

 

2. 주의점

  • OpenCVSharp4는 여러개의 Nuget으로 나워져 있음
  • 한 개라도 없으면 함수 또는 자료형의 일부를 찾을 수 없음

 

3. 설치 (Nuget Package Manager)


- WPF 환경에서 사용하기 위해 초록색 박스 부분 (OpenCvSharp4, OpenCvSharp4.runtime.win, OpenCvSharp4.WpfExtentions) 설치

- 윈도우 환경이라면 빨간색 박스 부분 설치가 더 간편함 (OpenVcSharp4.Windows)

 

 

4. OpenVcSharp4.Windows (빨간 박스) 설치 완료

참조

 

728x90
반응형
728x90
반응형

1. Visual Studio 2022 Community 설치

.NET 데스크톱 개발 선택 후 설치

 

2. 새 프로젝트 만들기 > WPF 앱 (.NET Framework) 선택

프로젝트 생성


프로젝트 생성 2

 

3. XAML/ 디자인 편집기와 C# 편집기

xaml/디자인 편집기


C# 편집기

 

4. 빌드 및 실행

빌드 및 실행 성공

728x90
반응형

+ Recent posts