cv.drawContours - MATLAB File Help
cv.drawContours

Draws contours outlines or filled contours

im = cv.drawContours(im, contours)
im = cv.drawContours(im, contours, 'OptionName', optionValue, ...)

Input

Output

Options

The function draws contour outlines in the image if Thickness >= 0 or fills the area bounded by the contours if Thickness < 0.

Example

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')

Note

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.

See also