Skip to content

v1

count_specific_color_pixels(image, target_color, tolerance)

Counts the number of pixels that match the target color within the given tolerance.

Parameters:

Name Type Description Default
image ndarray

Input image.

required
target_color Union[str, tuple]

Target color in hex format (e.g., '#431112') or BGR tuple (e.g., (18, 17, 67)).

required
tolerance int

Tolerance for color matching. Defaults to 10.

required

Returns:

Name Type Description
int int

Number of pixels that match the target color.

Source code in inference/core/workflows/core_steps/classical_cv/pixel_color_count/v1.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def count_specific_color_pixels(
    image: np.ndarray,
    target_color: Union[str, Tuple[int, int, int]],
    tolerance: int,
) -> int:
    """
    Counts the number of pixels that match the target color within the given tolerance.

    Args:
        image: Input image.
        target_color (Union[str, tuple]): Target color in hex format (e.g., '#431112') or BGR tuple (e.g., (18, 17, 67)).
        tolerance (int, optional): Tolerance for color matching. Defaults to 10.

    Returns:
        int: Number of pixels that match the target color.
    """
    target_color_bgr = convert_color_to_bgr_tuple(color=target_color)
    lower_bound = np.array(
        [
            target_color_bgr[0] - tolerance,
            target_color_bgr[1] - tolerance,
            target_color_bgr[2] - tolerance,
        ]
    )
    upper_bound = np.array(
        [
            target_color_bgr[0] + tolerance,
            target_color_bgr[1] + tolerance,
            target_color_bgr[2] + tolerance,
        ]
    )
    mask = cv2.inRange(image, lower_bound, upper_bound)
    return int(np.sum(mask > 0))