Favicon

Crop image

Peponi2/19/20252m

C#
NugetPackageOpenCvSharp4

1. Introduction

OpenCvSharp4에는 Mat 클래스를 통해 이미지에 접근할 수 있다. 이 문서에서는 Mat 클래스를 통해 이미지에서 ROI (Region of interest) 를 추출하는 몇 가지 방법을 간략히 알아본다.

  • Mat.SubMat()
  • Indexer (Mat[])
  • Ctor (new Mat())

실습에 사용할 이미지는 다음과 같다.

Image by sebastian del val from Pixabay

실습을 진행할 ROI는 다음 이미지에 붉은 box로 표시되어 있다.

roi

2. SubMat

submat result

private void SubMat(Mat image)
{
    // Rect(X, Y, Width, Height)
    using var cropped = image.SubMat(new Rect(200, 100, 300, 150));
}

3. Indexer

indexer result

private void Indexer(Mat image)
{
    // Mat[rowStart, rowEnd, colStart, colEnd]
    using var cropped = image[100, 250, 200, 500];
}

4. Ctor

ctor result

private void Ctor(Mat image)
{
    using var cropped = new Mat(image, new Rect(200, 100, 300, 150));
}

5. 참조 자료