问题描述
我的图像很小. 在此处输入图片描述b g r,不是灰色.
I have small image. enter image description hereb g r, not gray.
original = cv2.imread('im/auto5.png')
print(original.shape) # 27,30,3
print(original[13,29]) # [254 254 254]
如您所见,我的图像中有白色的图片(数字14),大部分是黑色的.在右上角(坐标[13,29])我得到[254 254 254]-白色.
As you can see, there is white pic (digit 14) in my image, mostly black. On the right corner (coordinates [13,29]) I get [254 254 254] - white color.
我想计算该特定颜色的像素数.我需要它来进一步比较内部具有不同数字的此类图像.这些方块有不同的背景,我认为正是白色.
I want to calculate number of pixels with that specific color. I need it to further comparing such images with different numbers inside. There are different backgrounds on these squares, and I consider exactly white color.
推荐答案
我会使用numpy
做到这一点,该向量被矢量化并且比使用for
循环要快得多:
I would do that with numpy
which is vectorised and much faster than using for
loops:
#!/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()
相同:
It will work just the same with OpenCV's imread()
:
#!/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)
这篇关于在图像上获取具有特定颜色的像素数量. Python,OpenCV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!