IT/C#

[C#] OpenCvSharp4 사용하여 이미지 발광영역 Rectangle 검출하기

Ella.J 2025. 8. 25. 10:51
728x90
반응형

 

Bitmap 이미지에서 밝은 영역의 사각형(Rectangle)을 검출하는 OpenCvSharp C# 예제 코드


[Visual Studio NuGet Package 설치]


[원본 이미지, 결과 이미지 미리보기]

 


[코드 설명]

 

  1. 이미지 로드
  2. Grayscale 변환
  3. 밝은 영역 마스크 생성 (Threshold)
  4. Contour(윤곽선) 검출
  5. 윤곽선의 BoundingRect 계산
  6. 원본 이미지에 사각형 표시 후 저장
  • Cv2.Threshold: 픽셀 값이 100 이상이면 흰색(255), 아니면 검은색(0)으로 변환.
  • Cv2.FindContours: 밝은 영역의 윤곽선 탐색.
  • Cv2.BoundingRect: 윤곽선의 최소 Bounding Box 계산.
  • 작은 노이즈 제거를 위해 최소 크기 조건 추가.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using OpenCvSharp;
 
class Program
{
    static void Main()
    {
        // 이미지 경로
        string imagePath = "Original.bmp";
 
        // 1. 이미지 로드
        Mat src = Cv2.ImRead(imagePath);
 
        if (src.Empty())
        {
            Console.WriteLine("이미지를 불러올 수 없습니다.");
            return;
        }
 
        // 2. Grayscale 변환
        Mat gray = new Mat();
        Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
 
        // 3. Threshold로 밝은 영역 마스크 생성
        Mat thresh = new Mat();
        Cv2.Threshold(gray, thresh, 100255, ThresholdTypes.Binary); // 100 이상을 밝은 영역으로 판단
 
        // 4. Contour 검출
        Cv2.FindContours(thresh, out Point[][] contours, out HierarchyIndex[] hierarchy,
                         RetrievalModes.External, ContourApproximationModes.ApproxSimple);
 
        // 5. 각 Contour에 대해 BoundingRect 계산 및 그리기
        foreach (var contour in contours)
        {
            Rect rect = Cv2.BoundingRect(contour);
 
            // 너무 작은 노이즈는 제외 (예: 너비/높이 10px 이상)
            if (rect.Width > 10 && rect.Height > 10)
            {
                Cv2.Rectangle(src, rect, new Scalar(00255), 2);
            }
        }
 
        // 6. 결과 저장
        Cv2.ImWrite("Result.bmp", src);
 
        Console.WriteLine("밝은 영역의 Rectangle 검출 완료: Result.bmp");
    }
}
 
cs

 

 

728x90
반응형