C#/C# OpenCV/

C# OpenCV 7-1. Contour(1) 윤곽선 찾기

2019. 12. 6.

대표함수

Cv2.CvtColor 색공간 변환 [프로그래밍/C# OpenCV] - C# OpenCV 5-1. 색공간 변환

Cv2.Threshold 이진화 [프로그래밍/C# OpenCV] - C# OpenCV 4-2. Binary

Cv2.FindContours 윤곽점 찾기

Cv2.DrawContours 윤곽 그리기

 

Example Code

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

namespace findContour
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Mat src = new Mat("image.png");
            Mat src1 = new Mat(), src2 = new Mat();
            src.CopyTo(src1);
            src.CopyTo(src2);
            Cv2.ImShow("scr", src);

            Mat bin = new Mat();
            Cv2.CvtColor(src, bin, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(bin, bin, 127, 255, ThresholdTypes.Binary);

            Mat hierarchy1 = new Mat();
            Cv2.FindContours(bin, out Mat[] contour1, hierarchy1,
                RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
                
            for (int i = 0; i &lt contour1.Length; i++)
            {
                Cv2.DrawContours(src2, contour1, i, Scalar.Red, 3, LineTypes.AntiAlias);
            } 
            Cv2.ImShow("1", src1);

            Cv2.FindContours(bin, out Point[][] contour2, out HierarchyIndex[] hierarchy2,
                RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
                
            for (int i = 0; i &lt contour2.Length; i++)
            {
                Cv2.DrawContours(src2, contour2, i, Scalar.Yellow, 3, LineTypes.AntiAlias);
            }
            Cv2.ImShow("2", src2);

            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

 

Explain Code

	    Mat src = new Mat("image.png");
            Mat src1 = new Mat(), src2 = new Mat();
            src.CopyTo(src1);
            src.CopyTo(src2);
            Cv2.ImShow("scr", src);

            Mat bin = new Mat();
            Cv2.CvtColor(src, bin, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(bin, bin, 127, 255, ThresholdTypes.Binary);
            

필요한 요소들 선언

원본이미지 이진화

FindContour 자체가 검은 배경에서 흰색 물체를 찾는 원리

 따라서 찾으려고 하는부분을 흰색으로 하게끔 이진화 필요

 

	    Mat hierarchy1 = new Mat();
            Cv2.FindContours(bin, out Mat[] contour1, hierarchy1,
                RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
                
            for (int i = 0; i &lt contour1.Length; i++)
            {
                Cv2.DrawContours(src1, contour1, i, Scalar.Red, 3, LineTypes.AntiAlias);
            } 
            Cv2.ImShow("1", src1);
            

※ 오버로드 1

Cv2.FindContours(i/o image, out Mat[] contours, output hierarchy,

                       RetrievalModes, ContourApproximationModes)

      image Contour를 찾을 이미지

      contours Contour 정보

      hierarchy Contour 계층 정보

      RetrievalModes 검색 방법

EXTERNAL 외곽 윤곽만 검출, 계층 정보 구성 X
LIST 모든 윤곽 검출, 계층 정보 구성 X
CCOMP 모든 윤곽 검출, 계층 정보 2단계 구성
TREE 모든 윤곽 검출, 계층 정보 모두 형성

      ContourApproximationModes 근사화 방법

ApproxNone 모든 윤곽점을 반환
ApproxSimple 윤곽점들 단순화, 수평,수직,대각선 요소를 압축 끝점만 반환
ApproxTC89L1 프리먼 체인 코드에서의 윤곽선 적용
ApproxTC89KCOS 프리먼 체인 코드에서의 윤곽선 적용

For문

for문을 통하여 획득한 contour의 길이만큼 반복하며 coutour그리기

 

 

Cv2.DrawContours(i/o image, System.Collections.Generic.IEnumerable<Mat> contours, int contourIdx,

                        Scalar color, int thickness, LineTypes)

      image contour를 그릴 이미지

      contours contour정보가 담긴 Mat[]

      contourIdx 계층 Index

      color 윤곽선 색상

      thickness 윤곽선 두께

      LineTypes 윤곽선 보정

 

	    Cv2.FindContours(bin, out Point[][] contour2, out HierarchyIndex[] hierarchy2,
                RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
                
            for (int i = 0; i &lt contour2.Length; i++)
            {
                Cv2.DrawContours(src2, contour2, i, Scalar.Yellow, 3, LineTypes.AntiAlias);
            }
            Cv2.ImShow("2", src2);
            

※ 오버로드 2

Cv2.FindContours(i/o image, out point[][] contours, out HierarchyIndex hierarchy,

                       RetrievalModes, ContourApproximationModes)

      image Contour를 찾을 이미지

      contours Contour 정보

      hierarchy Contour 계층 정보

      RetrievalModes 검색 방법

      ContourApproximationModes 근사화 방법

 

For문

for문을 통하여 획득한 contour의 길이만큼 반복하며 coutour그리기

 

Cv2.DrawContours(i/o image, System.Collections.Generic.IEnumerable<point> contours, int contourIdx,

                        Scalar color, int thickness, LineTypes)

      image contour를 그릴 이미지

      contours contour정보가 담긴 point[][]

      contourIdx 계층 Index

      color 윤곽선 색상

      thickness 윤곽선 두께

      LineTypes 윤곽선 보정

 

결과

※ 오버로드 1, 2 의 결과는 동일하다