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

前端 未结 2 973
星月不相逢
星月不相逢 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条回答
  • 2021-01-15 02:30

    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)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题