stouputils.data_science.data_processing.image.binary_threshold module#
- binary_threshold_image(image: ndarray[Any, dtype[Any]], threshold: float, ignore_dtype: bool = False) ndarray[Any, dtype[Any]] [source]#
Apply binary threshold to an image.
- Parameters:
image (NDArray[Any]) – Image to threshold
threshold (float) – Threshold value (between 0 and 1)
ignore_dtype (bool) – Ignore the dtype check
- Returns:
Thresholded binary image
- Return type:
NDArray[Any]
>>> ## Basic tests >>> image = np.array([[100, 150, 200], [50, 125, 175], [25, 75, 225]]) >>> binary_threshold_image(image.astype(np.uint8), 0.5).tolist() [[0, 255, 255], [0, 0, 255], [0, 0, 255]]
>>> np.random.seed(42) >>> img = np.random.randint(0, 256, (4,4), dtype=np.uint8) >>> thresholded = binary_threshold_image(img, 0.7) >>> set(np.unique(thresholded).tolist()) <= {0, 255} # Should only contain 0 and 255 True
>>> rgb = np.random.randint(0, 256, (3,3,3), dtype=np.uint8) >>> thresh_rgb = binary_threshold_image(rgb, 0.5) >>> thresh_rgb.shape == rgb.shape True >>> set(np.unique(thresh_rgb).tolist()) <= {0, 255} True
>>> ## Test invalid inputs >>> binary_threshold_image("not an image", 0.5) Traceback (most recent call last): ... AssertionError: Image must be a numpy array
>>> binary_threshold_image(image.astype(np.uint8), "0.5") Traceback (most recent call last): ... AssertionError: threshold must be a number, got <class 'str'>
>>> binary_threshold_image(image.astype(np.uint8), 1.5) Traceback (most recent call last): ... AssertionError: threshold must be between 0 and 1, got 1.5