opencv를 활용한 이미지 외곽선 검출 FindContours 함수 활용
본문 바로가기
영상처리

opencv를 활용한 이미지 외곽선 검출 FindContours 함수 활용

by 124578 2022. 2. 17.

이미지 외곽선을 검출하는 방법에대해 포스팅합니다. 컴퓨터가 이미지의 외곽선을 검출하여 기하학적 형태의 패턴을 검출하는 방법입니다. 주로 Opencv에 대부분의 알고리즘이 라이브러리 형태로 잘 정리되어 있습니다. 

 

아래 이미지의 외곽선을 검출하는 방법에 대해 알아봅니다.

입력이미지

세모, 네모, 원의 이미지의 외곽선을 찾아 보겠습니다. 이미지의 외곽선을 찾는 것은 opencv에서 제공하는 FindContours함수를 활용합니다. 이함수는 이미지의 윤곽을 검출하는 용도로 사용할 수 있습니다.

 

 

아래는 소스코드 입니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;
using Point = OpenCvSharp.Point;

 


namespace FindContours
{

    private void Form1_Load(object sender, EventArgs e)
    {

            Mat src = new Mat("image.png");
            Mat result = new Mat();
            Mat bin = new Mat(); src.CopyTo(result);
            Cv2.CvtColor(src, bin, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(bin, bin, 0, 255, ThresholdTypes.Otsu); Cv2.ImShow("src", src);
            Cv2.FindContours(bin, out Point[][] contour, out HierarchyIndex[] hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);

            for (int i = 0; i < contour.Length; i++)
            {
                Cv2.DrawContours(result, contour, i, Scalar.Green, 2, LineTypes.AntiAlias, hierarchy);
            }
            Cv2.ImShow("result", result);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }

 }

 

 

코드 설명 입니다.

 Cv2.CvtColor(src, bin, ColorConversionCodes.BGR2GRAY);

색상을 컬러에서 그레이 스케일 이미지로 변환해 줍니다.

 

  Cv2.Threshold(bin, bin, 0, 255, ThresholdTypes.Otsu); Cv2.ImShow("src", src);

이미지를 이진화 처리합니다.

 

  Cv2.FindContours(bin, out Point[][] contour, out HierarchyIndex[] hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);

 

외곽선 검출을 위한 함수를 실행합니다. contour 포인트 배열에 외곽포인트점들이 추출되어 저장 됩니다.

 

for (int i = 0; i < contour.Length; i++)
{
        Cv2.DrawContours(result, contour, i, Scalar.Green, 2, LineTypes.AntiAlias, hierarchy);

 }

 

contour 포인트 배열에 저장된 포인트를 기반으로 외곽선을 그려줍니다.

 

Cv2.ImShow("result", result);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();

 

이제 그린 이미지를 창에뜨워 보여줍니다.

 

결과 이미지는 아래와 같습니다. 윤곽에 녹색 선이 윤곽으로 생긴것을 확인할 수 있습니다.

 

 

findcontours 결과 화면
opencv findcontours 결과화면

크게 어렵지 않게 이미지의 외곽선을 찾을 수 있습니다. opencv를 이용하면 다양한 이미지처리를 쉽게 할 수 있습니다. 컴퓨터가 영상을 인식하는 방식에 대해 알 수 있습니다. 

 

 

댓글


TOP

TEL. 02.1234.5678 / 경기 성남시 분당구 판교역로