python读取图片中的所有颜色值_在图像上获取具有特定颜色的像素数量。 Python,OpenCV...

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[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.

解决方案

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)

你可能感兴趣的:(python读取图片中的所有颜色值_在图像上获取具有特定颜色的像素数量。 Python,OpenCV...)