【问题标题】:OpenCV - How to compute the percent of dark color in image?OpenCV - 如何计算图像中深色的百分比?
【发布时间】:2026-02-15 23:05:01
【问题描述】:

我想通过计算图像中深色的百分比来过滤图像。

这张图片中深色的百分比是0.05%,例如:

第二张图片中深色的百分比为0.5%:

【问题讨论】:

  • 与图像其余部分相比的比例?如果它们足够“暗”,您可以遍历所有像素值并计算它们。
  • import numpy as np; np.countNonZero(img)
  • @user1767754 你能给出一些示例代码吗?
  • 如果是二值图像,使用@ZdaR 所说的countNonZero,否则,使用阈值转换为二值图像然后countNonZero

标签: c++ opencv image-processing


【解决方案1】:

使用threshold to zero 将暗像素设置为零,然后使用cv::countNonZero() 计算非零值。

double getBlackProportion(cv::Mat img, double threshold)
{
    int imgSize = img.rows * img.cols;
    // you can use whathever for maxval, since it's not used in CV_THRESH_TOZERO
    cv::threshold(img, img, threshold, -1, CV_THRESH_TOZERO);
    int nonzero = cv::countNonZero(img);


    return (imgSize - nonzero) / double(imgSize);
}

【讨论】: