OpenCVSharp4でバウンディングボックスの描画

バウンディングボックスとは

ある領域を長方形(矩形)で囲むこと。
今回は水平&鉛直方向に伸びた矩形と、
斜めの矩形で検出する。

方法

OpenCVSharp4の導入はコチラ

  1. 画像を読み込み
  2. 二値化
  3. エッジ検出
  4. 輪郭検出
  5. 親輪郭からバウンディングボックスを描画する



バウンディングボックス作成には

  • Cv2.BounfingRect()水平な長方形で囲む
  • Cv2.MinAreaRect()最小の長方形で囲む

を使う

プログラム

using System;  
using System.Collections.Generic;  
using OpenCvSharp;  

namespace BoundingBoxAndCircles {  
    class Program {  
        static void Main(string[] args) {  
            //1.画像を読み込み  
            Mat src = new Mat(@"D:\Learning\OpenCV\thumbnail_small_star.jpg");  


            //2.二値化  
            Mat bw = src.CvtColor(ColorConversionCodes.BGR2GRAY);  
            Cv2.Threshold(bw, bw, 100, 255, ThresholdTypes.Otsu);  


            //3.エッジ検出  
            Mat edges = new Mat();  
            Cv2.Canny(bw, edges, 200, 20);  


            //4.輪郭検出  
            OpenCvSharp.Point[][] contours;  
            HierarchyIndex[] hierarchyIndices;  
            edges.FindContours(out contours, out hierarchyIndices, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple);  


            //5.親輪郭を構成する点を描画  
            Mat dst = src.Clone();  
            var points = new List<OpenCvSharp.Point>();  
            for(int i = 0; i < contours.GetLength(0); ++i) {  
                //親輪郭を集める  
                if(hierarchyIndices[i].Parent != -1) { continue; }  
                {  
                    //バウンディングボックスを計算  
                    var boundingBox = Cv2.BoundingRect(contours[i]);  
                    var minBox = Cv2.MinAreaRect(contours[i]);  

                    //バウンディングボックスの描画  
                    dst.Rectangle(boundingBox, Scalar.Red, 2);  
                    var pts = minBox.Points();  
                    for(int x = 0; x<pts.Length; x++) {  
                        Cv2.Line(dst, (int)pts[x].X, (int)pts[x].Y, (int)pts[(x + 1) % 4].X, (int)pts[(x + 1) % 4].Y, Scalar.Green, 2);  
                        Console.WriteLine(pts[x].X);  
                    }  
                }  

            }  


            //6.表示  
            Cv2.ImShow("dst", dst);  
            Cv2.ImWrite(@"D:\Learning\OpenCV\thumbnail_small_star2.jpg", dst);  
            Cv2.WaitKey();  

        }  
    }  
}