使用 OpenCV 在 Python 中计算图像中的黑色像素数 [英] count number of black pixels in an image in Python with OpenCV
问题描述
我在 Python 中有以下测试代码来读取、阈值和显示图像:
I have the following test code in Python to read, threshold and display an image:
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 的教程,但没有找到任何帮助:-(
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 :-(
谢谢!
推荐答案
对于黑色图像,您获得像素总数(行*列),然后从 cv2.countNonZero(mat)
.
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.inRange()
返回一个二进制掩码,显示您想要的颜色/标签/值的所有位置,然后使用 cv2.countNonZero
计算如何其中有很多.
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.
更新(根据 Miki 的评论):
UPDATE (Per Miki's comment):
当尝试查找具有特定值的元素的数量时,Python 允许您跳过 cv2.inRange()
调用,只需执行以下操作:
When trying to find the count of elements with a particular value, Python allows you to skip the cv2.inRange()
call and just do:
cv2.countNonZero(img == scalar_value)
这篇关于使用 OpenCV 在 Python 中计算图像中的黑色像素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!