diff --git a/include/detect/uv_led_detect_adaptive.cpp b/include/detect/uv_led_detect_adaptive.cpp index 211d465..0f2f903 100644 --- a/include/detect/uv_led_detect_adaptive.cpp +++ b/include/detect/uv_led_detect_adaptive.cpp @@ -604,6 +604,11 @@ std::tuple UVDARLedDetectAdaptive::findOptimalThresholdUsingKL(cons * @returns: * optimalThreshold: The optimal threshold */ + + + if (roiImage.empty()) { + throw std::runtime_error("Input image is empty."); + } // Calculate the histogram of the ROI image int histSize = 256; @@ -613,6 +618,11 @@ std::tuple UVDARLedDetectAdaptive::findOptimalThresholdUsingKL(cons cv::calcHist(&roiImage, 1, 0, cv::Mat(), hist, 1, &histSize, &histRange, true, false); cv::normalize(hist, hist, 1, 0, cv::NORM_L1, -1, cv::Mat()); + + if (cv::sum(hist)[0] == 0) { + throw std::runtime_error("Histogram normalization failed."); + } + double minKLDivergence = std::numeric_limits::max(); int optimalThreshold = 0; @@ -633,6 +643,8 @@ std::tuple UVDARLedDetectAdaptive::findOptimalThresholdUsingKL(cons double sumBelow = std::accumulate(P_below.begin(), P_below.end(), 0.0); double sumAbove = std::accumulate(P_above.begin(), P_above.end(), 0.0); + if (sumBelow == 0 || sumAbove == 0) continue; // Skip invalid cases + std::for_each(P_below.begin(), P_below.end(), [sumBelow](double& d) { d /= sumBelow; }); std::for_each(P_above.begin(), P_above.end(), [sumAbove](double& d) { d /= sumAbove; });