Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Sep 21st, 2012  |  syntax: None  |  size: 1.17 KB  |  hits: 84  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. require 'opencv'
  2. include OpenCV
  3.  
  4. # (1)画像を読み込んで2値化
  5. img = CvMat.load('lenna.png') # ※適当な画像を指定してください
  6. gray = img.BGR2GRAY
  7. bin = gray.threshold(100, 255, :binary)
  8.  
  9. # (2)近似対象の輪郭線を取得
  10. contours = bin.find_contours(:mode => CV_RETR_EXTERNAL)
  11.  
  12. # (3)全輪郭線をapprox_polyで近似
  13.  
  14. # CvContour#approx_poly(approx_poly_option)
  15. # 引数:
  16. #   approx_poly_option (Hash)…近似オプション
  17. #     :method - 近似手法。Douglas-Peuckerアルゴリズム(:dp)のみ。[cvApproxPolyの引数methodに対応]
  18. #     :accuracy - Douglas-Peuckerアルゴリズムの近似精度[cvApproxPolyの引数parameterに対応]
  19. #     :recursive - trueなら全部近似、falseなら1つのシーケンスのみ近似[cvApproxPolyの引数parameter2に対応]
  20. # 戻り値:
  21. #   近似された折れ線(CvContour)
  22. poly = contours.approx_poly(:method => :dp, :accuracy => 2.0, :recursive => true)
  23.  
  24. # (4)描画して表示
  25. begin
  26.   img.draw_contours!(poly, CvColor::Blue, CvColor::Black, 2,
  27.                      :thickness => 1, :line_type => :aa)
  28. end while (poly = poly.h_next)
  29. window = GUI::Window.new('approx_poly')
  30. window.show img
  31. GUI::wait_key