OpenCvSharpで、画像を二値化する方法はグレースケールしてから、Cv.Thresholdで二値化します。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |         //using OpenCvSharp;         private IplImage getBinImage()         {             //元の画像を読込             IplImage img = new IplImage("test.jpg");             //二値化画像を保存するIplImageの準備             IplImage bin_iplImg = new IplImage(img.Width, img.Height, BitDepth.U8, 1);             //閾値             int threshould = 180;             //グレースケールに変換             img.CvtColor(bin_iplImg, ColorConversion.BgrToGray);             //二値化処理             Cv.Threshold(bin_iplImg, bin_iplImg, threshould, 255, ThresholdType.Binary);             return bin_iplImg;         } | 
でも、RGB各要素で閾値を変えたい場合、たとえば、緑成分の多い画像を処理したい時などには次のようにします。
| 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 |         //using OpenCvSharp;         IplImage getBinImage2()         {             //元の画像を読込             IplImage img = new IplImage("test.jpg");             //二値化画像を保存するIplImageの準備             IplImage bin_iplImg = Cv.CreateImage(img.Size, BitDepth.U8, 1);             //RGB要素のIplImageの準備             IplImage r_iplImg = Cv.CreateImage(img.Size, BitDepth.U8, 1);             IplImage g_iplImg = Cv.CreateImage(img.Size, BitDepth.U8, 1);             IplImage b_iplImg = Cv.CreateImage(img.Size, BitDepth.U8, 1);             //元画像をRGBに分解             Cv.Split(img, b_iplImg, g_iplImg, r_iplImg, null);             //RGB各要素の閾値             int r_threshold = 180;             int g_threshold = 230;             int b_threshold = 150;             // 各RGB要素で閾値以下のピクセルを抽出する             Cv.Threshold(r_iplImg, r_iplImg, r_threshold, 255, ThresholdType.BinaryInv);              Cv.Threshold(g_iplImg, g_iplImg, g_threshold, 255, ThresholdType.BinaryInv);              Cv.Threshold(b_iplImg, b_iplImg, b_threshold, 255, ThresholdType.BinaryInv);              // ORでRGB要素を合算             Cv.Or(b_iplImg, g_iplImg, bin_iplImg, null);             Cv.Or(bin_iplImg, r_iplImg, bin_iplImg, null);             return bin_iplImg;         } | 
 
  
  
  
  
