Get a quanity of pixels with specific color at image. Python, opencv

前端 未结 2 988
星月不相逢
星月不相逢 2021-01-15 02:27

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         


        
2条回答
  •  Happy的楠姐
    2021-01-15 02:44

    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)
    

提交回复
热议问题