问题描述
我在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中计算图像中黑色像素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!