This must be simple for C++ developers using OpenCV directly. However what I'm using is Emgu (an OpenCV wrapper for .NET) and in the latest version we have the method CvInvoke.FindContours
returning void, the output result is passed by parameter reference and is of type VectorOfVectorOfPoint
.
Here is a simple call:
//outputResult is a VectorOfVectorOfPoint
CvInvoke.FindContours(inputImage, outputResult, null, RetrType.Tree,
ChainApproxMethod.ChainApproxSimple);
For RetrType.List
mode, we can just convert the result to some array of arrays and loop through all the contours easily. However here I would like to navigate through all the contours in a tree. I guess we must do something with native (unsafe) C++ code here with pointer (accessed via the Ptr
property of the output result). But I wonder if there is a more .NET-friendly solution for this. And if even using pointer is the only solution, I still don't know how to delve into that Ptr
to navigate through the contours tree.
The sample codes accompanied with the Emgu installation have a snippet using CvInvoke.FindContourTree
instead (and that returns a int[,]
).
To obtain the hierarchy of the contours, you must first pass a Mat
object to the function:
Mat hierarchy = new Mat() ;
CvInvoke.FindContours(inputImage, outputResult, hierarchy, RetrType.Tree,
ChainApproxMethod.ChainApproxSimple);
Then you can use the hierarchy
object as follows (see here for more details in Python OpenCV) :
hierarchy
will be a Mat
object of size 1 x size of outputResult
x 4.
So for the contour with index i
:
hierachy[0,i,0]
is the index of the next contour at the same hierarchy level (with the same parent) or - 1 if it doesn't existhierachy[0,i,1]
is the index of the previous contour at the same hierarchy level or - 1 if it doesn't existhierachy[0,i,2]
is the index of the child of contouri
or - 1 if it doesn't existhierachy[0,i,3]
is the index of the parent of contouri
or - 1 if it doesn't exist
That's how you use the hierarchy object.
The contours themselves are accessed through the outputResult
object by using their indices.
来源:https://stackoverflow.com/questions/37408481/navigate-through-hierarchy-of-contours-found-by-findcontours-method