Created
November 5, 2013 16:47
-
-
Save ser1zw/7322004 to your computer and use it in GitHub Desktop.
A sample code of CvMat#find_contours to get multiple polygons in an image.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'opencv' | |
# Prepare a sample image (I used an image in this article: http://opencv-srf.blogspot.se/2011/09/object-detection-tracking-using-contours.html) | |
# $ wget http://4.bp.blogspot.com/-r36OpIdjPWE/UDPMJ2kPFZI/AAAAAAAAAPs/-eO4W_XeDo0/s1600/FindingContours.png | |
cvMat = OpenCV::CvMat.load('FindingContours.png', 0) | |
img = cvMat.GRAY2BGR | |
polygons = [] | |
# CvMat#find_contours returns CvChain when the mode is CV_CHAIN_CODE, or returns CvContour when the mode is one of the others. | |
# This method never returns CvSeq, but it is not a problem because CvContour extends CvSeq. | |
find_contours_result = cvMat.find_contours(:mode => OpenCV::CV_RETR_CCOMP, :method => OpenCV::CV_CHAIN_APPROX_SIMPLE) | |
puts find_contours_result.class #=> OpenCV::CvContour | |
while find_contours_result | |
polygons << find_contours_result.approx_poly(:recursive => true) | |
# Obtain the next contour | |
# You can get multiple polys in this way. | |
find_contours_result = find_contours_result.h_next | |
end | |
# Show each polygon | |
polygons.each_with_index do |polygon, i| | |
points = polygon.map { |p| "(#{p.x}, #{p.y})" }.join(', ') | |
puts "#{i}: #{points}" | |
img.poly_line!([polygon.to_a], :color => OpenCV::CvColor::Red, :thickness => 4, :is_closed => true) | |
end | |
w = OpenCV::GUI::Window.new('Result') | |
w.show img | |
OpenCV::GUI::wait_key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment