使用 OpenCV 在 Python 中计算图像中的黑色像素数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32590932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
count number of black pixels in an image in Python with OpenCV
提问by Aurélie JEAN
I have the following test code in Python to read, threshold and display an image:
我在 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()
I would like to count the number of pixels within the image with a certain label, for instance black. How can I do that ? I looked at tutorials of OpenCV but did not find any help :-(
我想用某个标签(例如黑色)计算图像中的像素数。我怎样才能做到这一点 ?我查看了 OpenCV 的教程,但没有找到任何帮助:-(
Thanks!
谢谢!
采纳答案by Rick Smith
For black images you get the total number of pixels (rows*cols) and then subtract it from the result you get from cv2.countNonZero(mat)
.
对于黑色图像,您将获得像素总数(行*列),然后从您获得的结果中减去它cv2.countNonZero(mat)
。
For other values, you can create a mask using cv2.inRange()
to return a binary mask showing all the locations of the color/label/value you want and then use cv2.countNonZero
to count how many of them there are.
对于其他值,您可以创建一个掩码,cv2.inRange()
用于返回一个二进制掩码,显示您想要的颜色/标签/值的所有位置,然后用于cv2.countNonZero
计算它们中有多少。
UPDATE (Per Miki's comment):
更新(根据 Miki 的评论):
When trying to find the count of elements with a particular value, Python allows you to skip the cv2.inRange()
call and just do:
当尝试查找具有特定值的元素计数时,Python 允许您跳过cv2.inRange()
调用并执行以下操作:
cv2.countNonZero(img == scalar_value)
回答by Danny
import cv2
image = cv2.imread("pathtoimg", 0)
count = cv2.countNonZero(image)
print(count)