【问题标题】:Printing the percentage of a color in an image in OpenCV Python在 OpenCV Python 中打印图像中颜色的百分比
【发布时间】:2020-02-13 16:50:30
【问题描述】:

我有这个 python 脚本,它接收图像并输出该图像中绿色和棕色的百分比。我需要帮助来理解下面所说的行,因为我想用另一种语言实现这段代码。

    img = cv2.imread('__FILE_LOCATION__')
    grid_HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    lower_green = np.array([25,52,72])
    upper_green = np.array([102,255,255])

    lower_brown = np.array([10, 100, 20])
    upper_brown = np.array([20, 255, 200])

    mask= cv2.inRange(grid_HSV, lower_green, upper_green)
    brown_mask= cv2.inRange(grid_HSV, lower_brown, upper_brown)

    print(str(round(((mask>0).mean())*100,3)))                 #<- This line
    print(str(round(((brown_mask>0).mean())*100,3)))           #<- and This line

    # what is "mask>0" part, ".mean()" part and why multiply with 100

下面是我上面的python代码的Java实现。它只是缺少百分比计算部分。我需要帮助来完成这项工作。

    oImage = imread(pathOfFile);
    hsvImage = new Mat();
    color_range1 = new Mat();
    color_range2 = new Mat();

    Imgproc.cvtColor(oImage, hsvImage, Imgproc.COLOR_BGR2HSV);
    Core.inRange(hsvImage, new Scalar(25,52,72), new Scalar(102,255,255), color_range1); // Green
    Core.inRange(hsvImage, new Scalar(10, 100, 20), new Scalar(20, 255, 200), color_range2); // Brown



    // Finding percentage of green and brown colors from above masks.



    color_range1.release();
    color_range2.release();
    hsvImage.release();
    oImage.release();

【问题讨论】:

  • 继续阅读object.__gt__
  • mask 是一个 numpy 数组。 mask&gt;0 返回一个 numpy 布尔数组,表示每个元素是否满足该条件。显然在布尔数组上调用mean 将每个False 视为0 并将每个True 视为1,并计算其平均值。乘以 100 你得到百分比。即mask 为非零(无符号)的值的百分比。由于maskinRange 调用的结果,它将匹配值设置为255,它是图像中绿色像素的百分比。
  • @Dan Mašek 我需要在 java 中实现这个 python 代码。我已经完成了 java 代码,直到 inRange 调用了两个掩码。你能帮我完成它来计算绿色和棕色的百分比吗?
  • @Dan Mašek 嘿,你能帮帮我吗???
  • 有一个函数Core.countNonZero(从名字上应该很明显),Mat.total() 给出了像素总数。

标签: python opencv colors


【解决方案1】:

获取您的蒙版,然后将具有颜色匹配(非零)的像素数除以总像素数(蒙版数组的大小)乘以 100。四舍五入到小数点后一位也不错:

round(np.count_nonzero(mask) / np.size(mask) * 100, 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 2020-05-12
    • 2020-05-29
    • 2014-02-23
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多