[英]Get a quanity of pixels with specific color at image. Python, opencv
I have small image.我有小形象。 enter image description here bg r, not gray.
在此处输入图像描述bg r,而不是灰色。
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.如您所见,我的图像中有白色图片(数字 14),大部分是黑色。 On the right corner (coordinates [13,29]) I get [254 254 254] - white color.
在右上角(坐标 [13,29])我得到 [254 254 254] - 白色。
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:我会用
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)
Sample Output样本输出
35
It will work just the same with OpenCV's imread()
:它与 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 NoTE ** BGR not RGB values match "sought", and count
result = np.count_nonzero(np.all(im==sought,axis=2))
print(result)
Image in cv2 is an iterable object. cv2 中的图像是一个可迭代对象。 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)
Try this:尝试这个:
import cv2
import numpy as np
img = cv2.imread("im/auto5.png")
color = [48,75,105] # set color to looking for
im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
result = np.count_nonzero(np.all(im==color,axis=2))
print("Total pixels " + str(result))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.