在图像上获取具有特定颜色的像素数量。Python,opencv

在图像上获取具有特定颜色的像素数量。Python,opencv,python,opencv,Python,Opencv,我有一张小照片。 b g r,不是灰色的 original = cv2.imread('im/auto5.png') print(original.shape) # 27,30,3 print(original[13,29]) # [254 254 254] 正如你所看到的,在我的图片中有白色的图片(数字14),大部分是黑色的。在右角(坐标[13,29])我得到[254 254]-白色 我想计算特定颜色的像素数。我需要它来进一步比较这些图片和里面不同的数字。在这些方格上有不同的背景,我认为

我有一张小照片。 b g r,不是灰色的

original = cv2.imread('im/auto5.png')
print(original.shape)  # 27,30,3 
print(original[13,29]) # [254 254 254]
正如你所看到的,在我的图片中有白色的图片(数字14),大部分是黑色的。在右角(坐标[13,29])我得到[254 254]-白色


我想计算特定颜色的像素数。我需要它来进一步比较这些图片和里面不同的数字。在这些方格上有不同的背景,我认为完全是白色的。 cv2中的图像是一个不可编辑的对象。因此,您可以遍历所有像素来计算要查找的像素

import os
import cv2
main_dir = os.path.split(os.path.abspath(__file__))[0]
file_name = 'im/auto5.png'
color_to_seek = (254, 254, 254)

original = cv2.imread(os.path.join(main_dir, file_name))

amount = 0
for x in range(original.shape[0]):
    for y in range(original.shape[1]):
        b, g, r = original[x, y]
        if (b, g, r) == color_to_seek:
            amount += 1

print(amount)

我会使用
numpy
来实现这一点,它是矢量化的,比使用
进行
循环要快得多:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Open image and make into numpy array
im=np.array(Image.open("p.png").convert('RGB'))

# Work out what we are looking for
sought = [254,254,254]

# Find all pixels where the 3 RGB values match "sought", and count them
result = np.count_nonzero(np.all(im==sought,axis=2))
print(result)
样本输出

35

对于OpenCV的
imread()
,它的工作原理是一样的:


欢迎来到堆栈溢出!你试过什么?您能给我们看一些代码吗?您的意思是要查找与坐标
[13,29]
处的像素匹配的所有像素,还是要查找
(254)
处的所有像素。我的意思是,如果
[13,29]
处的像素是
(8,7,6)
,您想查找什么?我想查找所有是(254)的像素。不是坐标,只是数量,这些像素的数量。是的,我想提出一些类似的建议:)谢谢!使用np.count_非零的方式比使用循环的方式更快。一个问题?axis=2是什么?我将
numpy
方式计时为22微秒,将等效的
for
循环计时为1.5毫秒,因此加快了68倍
axis=1
沿着图像的高度上下运行,
axis=2
从左到右穿过图像,
axis=3
沿着R、G和B进入图像。因此,通过说
np.all(im==Sequed,axis=2)
我的意思是R、G和B都等于
Sequed
。我做了编辑,但不确定它去了哪里。我认为这是一个很好的答案,但我想指出OpenCV代码使用的是BGR而不是RGB。谢谢
#!/usr/local/bin/python3
import numpy as np
import cv2

# Open image and make into numpy array
im=cv2.imread('p.png')

# Work out what we are looking for
sought = [254,254,254]

# Find all pixels where the 3 NoTE ** BGR not RGB  values match "sought", and count
result = np.count_nonzero(np.all(im==sought,axis=2))
print(result)