cv.drawContours - MATLAB File Help |
Draws contours outlines or filled contours
im = cv.drawContours(im, contours)
im = cv.drawContours(im, contours, 'OptionName', optionValue, ...)
{{[x,y],[x,y],...}, ...}
, or a cell array of Nx2 matrices.im
.[0,length(contours)-1]
. If it is negative, all the contours
are drawn. default -1MaxLevel
). A cell array
of 4-element vectors for each contour of the form
{[next,prev,child,parent], ...}
, or a Nx4/Nx1x4/1xNx4 numeric matrix of
integers. default emptyHierarchy
available. default intmax('int32')
offset = (dx,dy)
. default [0,0]The function draws contour outlines in the image if Thickness >= 0
or
fills the area bounded by the contours if Thickness < 0
.
The example below shows how to retrieve connected components from a binary image and label them:
% binary (black-n-white) image
src = cv.imread('bw.png', 'Flags',0);
src = logical(src > 0);
[contours,hierarchy] = cv.findContours(src, 'Mode','CComp', ...
'Method','Simple');
% iterate through all the top-level contours,
% draw each connected component with its own random color
dst = zeros([size(src),3], 'uint8');
idx = 0;
while idx >= 0
color = randi([0 255], [1 3], 'uint8');
dst = cv.drawContours(dst, contours, 'ContourIdx',idx, ...
'Color',color, 'Thickness','Filled', 'LineType',8, ...
'Hierarchy',hierarchy);
idx = hierarchy{idx+1}(1);
end
subplot(121), imshow(src), title('Source')
subplot(122), imshow(dst), title('Components')
When Thickness='Filled'
, the function is designed to handle connected
components with holes correctly even when no hierarchy date is provided.
This is done by analyzing all the outlines together using even-odd rule.
This may give incorrect results if you have a joint collection of separately
retrieved contours. In order to solve this problem, you need to call
cv.drawContours separately for each sub-group of contours, or iterate over
the collection using ContourIdx
parameter.