I have small image. enter image description here b g r, not gray.
original = cv2.imread(\'im/auto5.png\')
print(original.shape) # 27,30,3
print(original[1
Image in cv2 is an iterable object. So you can just iterate through all pixels to count the pixels you are looking for.
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)
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)
Sample Output
35
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)