diff --git a/plantcv/plantcv/threshold/threshold_methods.py b/plantcv/plantcv/threshold/threshold_methods.py index 62ff850ef..78d0057b8 100644 --- a/plantcv/plantcv/threshold/threshold_methods.py +++ b/plantcv/plantcv/threshold/threshold_methods.py @@ -170,6 +170,12 @@ def otsu(gray_img, object_type="light"): params.device += 1 + # If the grayscale image is all zeros, return copy of input image. + if np.count_nonzero(gray_img) == 0: + bin_img = np.copy(gray_img) + _debug(visual=bin_img, filename=os.path.join(params.debug_outdir, f"{params.device}_otsu_empty.png")) + return bin_img + # Threshold the image bin_img = _call_threshold(gray_img, 0, threshold_method, "_otsu_threshold_") diff --git a/tests/plantcv/threshold/test_threshold_methods.py b/tests/plantcv/threshold/test_threshold_methods.py index ef66aa83f..59ec4d634 100644 --- a/tests/plantcv/threshold/test_threshold_methods.py +++ b/tests/plantcv/threshold/test_threshold_methods.py @@ -255,3 +255,10 @@ def test_dual_channels_bad_channel(): pts = [(0, 0), (255, 255)] with pytest.raises(RuntimeError): _ = dual_channels(img, x_channel='wrong_ch', y_channel='index', points=pts, above=True) + +def test_otsu_empty_mask(): + """Test for PlantCV.""" + mask = np.zeros((100, 100)) + fmask = otsu(mask) + assert np.sum(fmask) == 0 +