【问题标题】:count number of black pixels in an image in Python with OpenCV使用 OpenCV 在 Python 中计算图像中黑色像素的数量
【发布时间】:2015-09-15 16:16:26
【问题描述】:

我在 Python 中有以下测试代码来读取、阈值和显示图像:

import cv2
import numpy as np 
from matplotlib import pyplot as plt

# read image
img = cv2.imread('slice-309.png',0)
ret,thresh = cv2.threshold(img,0,230, cv2.THRESH_BINARY)
height, width = img.shape
print "height and width : ",height, width
size = img.size
print "size of the image in number of pixels", size 

# plot the binary image
imgplot = plt.imshow(img, 'gray')
plt.show()

我想计算图像中带有特定标签的像素数,例如黑色。 我怎样才能做到这一点 ?我查看了 OpenCV 的教程,但没有找到任何帮助:-(

谢谢!

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    对于黑色图像,您将获得像素总数(行*列),然后从您从cv2.countNonZero(mat) 获得的结果中减去它。

    对于其他值,您可以使用cv2.inRange() 创建一个掩码以返回一个二进制掩码,显示您想要的颜色/标签/值的所有位置,然后使用cv2.countNonZero 计算它们的数量。

    更新(根据 Miki 的评论):

    当尝试查找具有特定值的元素的计数时,Python 允许您跳过 cv2.inRange() 调用并执行以下操作:

    cv2.countNonZero(img == scalar_value)  
    

    【讨论】:

    • 非常感谢!我尝试过,实际上在使用 cv2 时,我必须使用 countNonZero 而不是 CountNonZero 和 cv。另一个问题:当我执行 cv2.countNonZero(thresh) 时,我得到的是像素总数而不是非黑色的像素数......你知道为什么吗?
    • 我更新了答案,函数名不应该大写。看来您的所有像素都不是黑色的...尝试查看thresh,它可能不是您认为的那样。如果这不起作用,请在此问题上标记您的首选答案以表明它已解决并询问另一个显示您的代码的问题。在此处放置该问题的链接,我会为您提供更多帮助。
    • 对不起,它有效!再次感谢您的帮助!!!你是对的,我的阈值在我的函数阈值中没有很好地定义......
    • 好答案。在 python 中有相当于这个 C++ 代码countNonZero(img == scalar_value);?
    【解决方案2】:
    import cv2
    image = cv2.imread("pathtoimg", 0)
    count = cv2.countNonZero(image)
    print(count)
    

    【讨论】:

    • 欢迎来到 StackOverflow,感谢您的回答!请用一些描述如何解决手头问题的非代码文本更新您的答案。
    猜你喜欢
    • 2012-04-27
    • 2013-10-10
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多