我的图像很小。 enter image description here 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 254]-白色。
我想计算该特定颜色的像素数。我需要它来进一步比较内部具有不同数字的此类图像。这些方块有不同的背景,我认为正是白色。
答案 0 :(得分:1)
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)
答案 1 :(得分:1)
我会使用numpy
来做到这一点,它被向量化并且比使用for
循环快得多:
#!/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()
相同:
#!/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 RGB values match "sought", and count
result = np.count_nonzero(np.all(im==sought,axis=2))
print(result)