Favicon

Load & save image

Peponi2/10/20253m

C#
NugetPackageOpenCvSharp4

1. Introduction

Photo by Felix Mittermeier

이 문서에서는 OpenCvSharp4를 이용해 이미지를 불러오고 저장하는 방법을 알아본다.

이미지를 불러올 때 여러가지 읽기 모드가 지원된다. 읽기 모드는 아래 표를 참조한다.

NameValueDescription
Unchanged-1Return the loaded image as is (with alpha channel, otherwise it gets cropped)
Grayscale0Always convert image to the single channel grayscale image
Color1Always convert image to the 3 channel BGR color image
AnyDepth2Return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit
AnyColor4The image is read in any possible color format
LoadGdal8Use the GDAL driver for loading the image
* GDAL driver : GDAL is a translator library for raster and vector geospatial data formats that is released under an MIT style Open Source License by the Open Source Geospatial Foundation
ReducedGrayscale216Always convert image to the single channel grayscale image and the image size reduced 1/2
ReducedColor217Always convert image to the 3 channel BGR color image and the image size reduced 1/2
ReducedGrayscale432Always convert image to the single channel grayscale image and the image size reduced 1/4
ReducedColor433Always convert image to the 3 channel BGR color image and the image size reduced 1/4
ReducedGrayscale864Always convert image to the single channel grayscale image and the image size reduced 1/8
ReducedColor865Always convert image to the 3 channel BGR color image and the image size reduced 1/8
IgnoreOrientation128Do not rotate the image according to EXIF's orientation flag
* EXIF : Exchangeable image file format (officially Exif, according to JEIDA/JEITA/CIPA specifications) is a standard that specifies formats for images, sound, and ancillary tags used by digital cameras (including smartphones), scanners and other systems handling image and sound files recorded by digital cameras

2. Example

using OpenCvSharp;
 
namespace ImageLoadSave;
 
public partial class Form1 : Form
{
    private Mat _currentImage = new();
 
    public Form1()
    {
        InitializeComponent();
        InitializeViewArea();
    }
 
    private void Load_Click(object? sender, EventArgs e)
    {
        OpenFileDialog dialog = new()
        {
            Filter = "All files|*.*",
            InitialDirectory = $@"C:\",
            CheckPathExists = true,
            CheckFileExists = true
        };
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            // 이전 이미지 할당 해제
            _currentImage.Release();
 
            // 이미지 로드
            _currentImage = Cv2.ImRead(dialog.FileName, (ImreadModes)Enum.Parse(typeof(ImreadModes), (Controls.Find("ImageModes", true)[0] as ListBox)!.SelectedItem!.ToString()!));
 
            // PictureBox에 이미지 할당. OpenCvSharp4.Extensions 설치 필요
            (Controls.Find("ImageView", true)[0] as PictureBox)!.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(_currentImage);
        }
    }
 
    private void Save_Click(object? sender, EventArgs e)
    {
        SaveFileDialog dialog = new()
        {
            Filter = "Bitmap file|*.bmp",
            InitialDirectory = $@"C:\",
            CheckPathExists = true,
            AddExtension = true
        };
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            // 이미지 저장
            Cv2.ImWrite(dialog.FileName, _currentImage);
        }
    }
 
    private void InitializeViewArea()
    {
        PictureBox picture = new()
        {
            Name = "ImageView",
            Dock = DockStyle.Fill,
            SizeMode = PictureBoxSizeMode.StretchImage
        };
 
        // OpenCvSharp4 이미지 로드 옵션
        ListBox imageModes = new()
        {
            Name = "ImageModes",
            Dock = DockStyle.Fill
        };
        imageModes.Items.AddRange(Enum.GetNames(typeof(ImreadModes)));
        imageModes.SelectedIndex = 0;
 
        Button load = new()
        {
            Text = "LOAD",
            Dock = DockStyle.Fill
        };
        load.Click += Load_Click;
 
        Button save = new()
        {
            Text = "SAVE",
            Dock = DockStyle.Fill
        };
        save.Click += Save_Click;
 
        TableLayoutPanel panel = new()
        {
            ColumnCount = 3,
            RowCount = 2,
            Dock = DockStyle.Fill
        };
        panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33.33F));
        panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33.33F));
        panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 33.34F));
        panel.RowStyles.Add(new RowStyle(SizeType.Percent, 80));
        panel.RowStyles.Add(new RowStyle(SizeType.Percent, 20));
 
        panel.Controls.Add(picture, 0, 0);
        panel.SetColumnSpan(picture, 3);
 
        panel.Controls.Add(imageModes, 0, 1);
        panel.Controls.Add(load, 1, 1);
        panel.Controls.Add(save, 2, 1);
 
        this.Controls.Add(panel);
    }
}

3. 참조 자료