Skip to content

Commit

Permalink
Added KL undefined operations check
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Apr 16, 2024
1 parent 6a9a9db commit 53e7ac7
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions include/detect/uv_led_detect_adaptive.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,11 @@ std::tuple<int, double> 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;
Expand All @@ -613,6 +618,11 @@ std::tuple<int, double> 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<double>::max();
int optimalThreshold = 0;

Expand All @@ -633,6 +643,8 @@ std::tuple<int, double> 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; });

Expand Down

0 comments on commit 53e7ac7

Please sign in to comment.