본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 79편: 이미지 처리 애플리케이션 제작 - OpenCvSharp 활용

by wawManager 2025. 4. 22.

반응형

 

1. 강의 개요

이번 강의에서는 OpenCvSharp 라이브러리를 활용해 이미지 처리 애플리케이션을 제작합니다.
OpenCvSharp은 .NET 환경에서 OpenCV를 사용할 수 있도록 제공되는 라이브러리로,
이미지 로드, 편집(예: 그레이스케일 변환, 블러링), 저장 기능을 손쉽게 구현할 수 있습니다.
실습에서는 Windows Forms UI를 통해 이미지를 처리하고 결과를 시각적으로 확인합니다.


2. 학습 목표

  • OpenCvSharp을 사용해 이미지 로드, 편집, 저장 구현
  • 그레이스케일 변환, 블러링 등 이미지 필터 적용
  • PictureBox를 활용한 이미지 시각화
  • 파일 열기 및 저장 대화 상자 구현

3. 기능 요구사항

필수 기능

1️⃣ 이미지 로드:

  • 사용자가 선택한 이미지를 PictureBox에 표시

2️⃣ 이미지 필터:

  • 그레이스케일 변환, 블러링 등 기본 필터 적용

3️⃣ 이미지 저장:

  • 편집된 이미지를 파일로 저장

4️⃣ UI 구성 및 동작:

  • 로드, 필터, 저장 기능을 UI에서 실행

4. 실습: 이미지 처리 애플리케이션 제작

1️⃣ 사전 준비

  1. NuGet 패키지 설치:
    • Visual Studio에서 OpenCvSharp4OpenCvSharp4.Windows 패키지를 설치합니다.
    • 설치 명령:
      Install-Package OpenCvSharp4
      Install-Package OpenCvSharp4.Windows
      
  2. 폼 구성:
    • 폼(Form) 이름: Form1
    • 컨트롤 배치:

컨트롤 타입 이름 위치 크기

Button btnLoadImage 폼 상단 왼쪽 (100 x 30)
Button btnGrayscale 폼 상단 중앙 (100 x 30)
Button btnBlur 폼 상단 오른쪽 (100 x 30)
Button btnSaveImage 폼 상단 오른쪽 끝 (100 x 30)
PictureBox pictureBox 폼 하단 전체 (500 x 400)

📌 폼 디자인 예시:

--------------------------------------------------
| [Load Image] [Grayscale] [Blur] [Save Image]   |
--------------------------------------------------
|                [PictureBox - 이미지 표시]       |
--------------------------------------------------

2️⃣ 코드 작성

(1) 이미지 로드 및 표시

using System;
using System.Windows.Forms;
using OpenCvSharp;

namespace WindowsFormsApp_ImageProcessing
{
    public partial class Form1 : Form
    {
        private Mat _image; // OpenCvSharp의 이미지 객체

        public Form1()
        {
            InitializeComponent();
        }

        // 이미지 로드
        private void btnLoadImage_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "이미지 파일 (*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName;
                    LoadImage(filePath);
                }
            }
        }

        private void LoadImage(string filePath)
        {
            try
            {
                _image = Cv2.ImRead(filePath); // 이미지 로드
                DisplayImage(_image);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"이미지 로드 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // PictureBox에 이미지 표시
        private void DisplayImage(Mat image)
        {
            if (image != null)
            {
                pictureBox.Image?.Dispose();
                pictureBox.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(image);
            }
        }
    }
}

(2) 그레이스케일 변환 및 블러링

        // 그레이스케일 변환
        private void btnGrayscale_Click(object sender, EventArgs e)
        {
            if (_image == null)
            {
                MessageBox.Show("먼저 이미지를 로드하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                Mat grayImage = new Mat();
                Cv2.CvtColor(_image, grayImage, ColorConversionCodes.BGR2GRAY);
                _image = grayImage; // 변환된 이미지를 현재 이미지로 설정
                DisplayImage(_image);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"그레이스케일 변환 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 블러링 처리
        private void btnBlur_Click(object sender, EventArgs e)
        {
            if (_image == null)
            {
                MessageBox.Show("먼저 이미지를 로드하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                Mat blurredImage = new Mat();
                Cv2.GaussianBlur(_image, blurredImage, new OpenCvSharp.Size(15, 15), 0);
                _image = blurredImage; // 변환된 이미지를 현재 이미지로 설정
                DisplayImage(_image);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"블러링 처리 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

(3) 이미지 저장

        // 이미지 저장
        private void btnSaveImage_Click(object sender, EventArgs e)
        {
            if (_image == null)
            {
                MessageBox.Show("저장할 이미지를 먼저 로드하거나 편집하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = "이미지 파일 (*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveFileDialog.FileName;

                    try
                    {
                        Cv2.ImWrite(filePath, _image); // 이미지 저장
                        MessageBox.Show("이미지가 저장되었습니다.", "완료", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"이미지 저장 실패: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

(4) Designer 코드

        private void InitializeComponent()
        {
            this.btnLoadImage = new Button();
            this.btnGrayscale = new Button();
            this.btnBlur = new Button();
            this.btnSaveImage = new Button();
            this.pictureBox = new PictureBox();

            // Load Image Button 설정
            this.btnLoadImage.Location = new System.Drawing.Point(10, 10);
            this.btnLoadImage.Size = new System.Drawing.Size(100, 30);
            this.btnLoadImage.Text = "Load Image";
            this.btnLoadImage.Click += new EventHandler(this.btnLoadImage_Click);

            // Grayscale Button 설정
            this.btnGrayscale.Location = new System.Drawing.Point(120, 10);
            this.btnGrayscale.Size = new System.Drawing.Size(100, 30);
            this.btnGrayscale.Text = "Grayscale";
            this.btnGrayscale.Click += new EventHandler(this.btnGrayscale_Click);

            // Blur Button 설정
            this.btnBlur.Location = new System.Drawing.Point(230, 10);
            this.btnBlur.Size = new System.Drawing.Size(100, 30);
            this.btnBlur.Text = "Blur";
            this.btnBlur.Click += new EventHandler(this.btnBlur_Click);

            // Save Image Button 설정
            this.btnSaveImage.Location = new System.Drawing.Point(340, 10);
            this.btnSaveImage.Size = new System.Drawing.Size(100, 30);
            this.btnSaveImage.Text = "Save Image";
            this.btnSaveImage.Click += new EventHandler(this.btnSaveImage_Click);

            // PictureBox 설정
            this.pictureBox.Location = new System.Drawing.Point(10, 50);
            this.pictureBox.Size = new System.Drawing.Size(500, 400);
            this.pictureBox.BorderStyle = BorderStyle.FixedSingle;
            this.pictureBox.SizeMode = PictureBoxSizeMode.Zoom;

            // Form 설정
            this.ClientSize = new System.Drawing.Size(540, 480);
            this.Controls.Add(this.btnLoadImage);
            this.Controls.Add(this.btnGrayscale);
            this.Controls.Add(this.btnBlur);
            this.Controls.Add(this.btnSaveImage);
            this.Controls.Add(this.pictureBox);
            this.Text = "이미지 처리 애플리케이션";
        }

3️⃣ 실행 결과

1️⃣ 이미지 로드

  • "Load Image" 버튼 클릭 → 파일 선택 → PictureBox에 이미지 표시

2️⃣ 그레이스케일 변환 및 블러링

  • "Grayscale" 클릭 → 이미지가 흑백으로 변환
  • "Blur" 클릭 → 이미지가 블러링 처리

3️⃣ 이미지 저장

  • "Save Image" 클릭 → 저장 경로 선택 → 편집된 이미지 저장

5. 주요 개념 요약

  • OpenCvSharp: 이미지 처리 및 분석을 위한 라이브러리
  • Mat: OpenCvSharp에서 이미지 데이터를 저장하는 클래스
  • Cv2.ImRead/ImWrite: 이미지 읽기 및 쓰기
  • Cv2.CvtColor: 색상 변환(예: 그레이스케일 변환)
  • Cv2.GaussianBlur: 이미지 블러링 처리

 

📌 #CSharp #WindowsForms #OpenCvSharp #이미지처리 #그레이스케일 #블러링

반응형