Skip to content

v1

find_and_draw_contours(image, color=(255, 0, 255), thickness=3)

Finds and draws contours on the image.

Parameters:

Name Type Description Default
image ndarray

Input thresholded image.

required
color tuple

Color of the contour lines in BGR. Defaults to purple (255, 0, 255).

(255, 0, 255)
thickness int

Thickness of the contour lines. Defaults to 3.

3

Returns:

Name Type Description
tuple Tuple[ndarray, int]

Image with contours drawn and number of contours.

Source code in inference/core/workflows/core_steps/classical_cv/contours/v1.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def find_and_draw_contours(
    image: np.ndarray, color: Tuple[int, int, int] = (255, 0, 255), thickness: int = 3
) -> Tuple[np.ndarray, int]:
    """
    Finds and draws contours on the image.

    Args:
        image (np.ndarray): Input thresholded image.
        color (tuple, optional): Color of the contour lines in BGR. Defaults to purple (255, 0, 255).
        thickness (int, optional): Thickness of the contour lines. Defaults to 3.

    Returns:
        tuple: Image with contours drawn and number of contours.
    """
    # If not in grayscale, convert to grayscale
    if len(image.shape) == 3 and image.shape[2] == 3:
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Find contours
    contours, hierarchy = cv2.findContours(
        image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
    )

    # Draw contours on a copy of the original image
    contour_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    cv2.drawContours(contour_image, contours, -1, color, thickness)

    # Return the image with contours and the number of contours
    return contour_image, contours, hierarchy