我有小图。在此处输入图像描述 bgr,而不是灰色。
original = cv2.imread('im/auto5.png')
print(original.shape) # 27,30,3
print(original[13,29]) # [254 254 254]
Run Code Online (Sandbox Code Playgroud)
如您所见,我的图像中有白色图片(第 14 位),主要是黑色。在右上角(坐标 [13,29])我得到 [254 254 254] - 白色。
我想计算具有该特定颜色的像素数。我需要它来进一步比较内部不同数字的此类图像。这些方块上有不同的背景,我认为颜色正好是白色。
我会使用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)
Run Code Online (Sandbox Code Playgroud)
样本输出
35
Run Code Online (Sandbox Code Playgroud)
它与 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7473 次 |
| 最近记录: |