2008-08-19 11:01:28 -04:00
|
|
|
#!/usr/bin/env ruby
|
|
|
|
# convexhull.rb
|
2012-06-02 11:02:18 -04:00
|
|
|
# Draw contours and convexity defect points to captured image
|
2010-12-29 13:45:44 -05:00
|
|
|
require "rubygems"
|
2008-08-19 11:01:28 -04:00
|
|
|
require "opencv"
|
|
|
|
include OpenCV
|
|
|
|
|
|
|
|
window = GUI::Window.new("convexhull")
|
|
|
|
capture = CvCapture::open
|
|
|
|
|
2012-06-02 11:02:18 -04:00
|
|
|
accuracy = 1
|
|
|
|
t = window.set_trackbar("accuracy", 10, 1) { |v|
|
|
|
|
accuracy = v
|
2008-08-19 11:01:28 -04:00
|
|
|
}
|
|
|
|
|
2012-06-02 11:02:18 -04:00
|
|
|
circle_options = { :color => CvColor::Blue, :line_type => :aa, :thickness => -1 }
|
|
|
|
|
|
|
|
loop do
|
2008-08-19 11:01:28 -04:00
|
|
|
image = capture.query
|
2012-06-02 11:02:18 -04:00
|
|
|
|
|
|
|
# Calculate contours from a binary image
|
2008-08-19 11:01:28 -04:00
|
|
|
gray = image.BGR2GRAY
|
2012-06-02 11:02:18 -04:00
|
|
|
bin = gray.threshold(0x44, 0xFF, :binary)
|
|
|
|
contours = bin.find_contours
|
|
|
|
|
|
|
|
while contours
|
|
|
|
# Draw contours
|
|
|
|
poly = contours.approx(:accuracy => accuracy)
|
|
|
|
begin
|
|
|
|
image.draw_contours!(poly, CvColor::Red, CvColor::Black, 2,
|
|
|
|
:thickness => 2, :line_type => :aa)
|
|
|
|
end while (poly = poly.h_next)
|
2008-08-19 11:01:28 -04:00
|
|
|
|
2012-06-02 11:02:18 -04:00
|
|
|
# Draw convexity defects
|
|
|
|
hull = contours.convex_hull2(true, false)
|
|
|
|
contours.convexity_defects(hull).each { |cd|
|
|
|
|
image.circle!(cd.start, 3, circle_options)
|
|
|
|
image.circle!(cd.depth_point, 3, circle_options)
|
|
|
|
image.circle!(cd.end, 3, circle_options)
|
|
|
|
}
|
2008-08-19 11:01:28 -04:00
|
|
|
contours = contours.h_next
|
|
|
|
end
|
2012-06-02 11:02:18 -04:00
|
|
|
|
|
|
|
window.show image
|
|
|
|
exit if GUI::wait_key(1)
|
2008-08-19 11:01:28 -04:00
|
|
|
end
|
2012-06-02 11:02:18 -04:00
|
|
|
|