numpy.ndarray中的值计数

时间:2013-11-12 01:48:04

标签: python opencv numpy

有没有办法在纯粹numpy(或opencv)中执行以下操作?

img = cv2.imread("test.jpg")
counts = defaultdict(int)
for row in img:
    for val in row:
        counts[tuple(val)] += 1

问题是tuple(val)显然可以是2 ^ 24个不同值中的一个,因此不可能为每个可能的值设置一个数组,因为它是巨大的并且大多数为零,所以我需要更多高效的数据结构。

2 个答案:

答案 0 :(得分:4)

最快的方法是,如果图像以“粗糙”格式存储,即颜色平面尺寸是最后一个,并且最后一个维度是连续的,则采用每24位像素的np.void视图,然后通过np.uniquenp.bincount运行结果:

>>> arr = np.random.randint(256, size=(10, 10, 3)).astype(np.uint8)
>>> dt = np.dtype((np.void, arr.shape[-1]*arr.dtype.itemsize))
>>> if arr.strides[-1] != arr.dtype.itemsize:
...     arr = np.ascontiguousarray(arr)
... 
>>> arr_view = arr.view(dt)

arr_view的内容看起来像垃圾:

>>> arr_view [0, 0]
array([Â], 
      dtype='|V3')

但是我们不得不理解内容:

>>> unq, _ = np.unique(arr_view, return_inverse=True)
>>> unq_cnts = np.bincount(_)
>>> unq = unq.view(arr.dtype).reshape(-1, arr.shape[-1])

现在你在这两个数组中拥有唯一的像素及其数量:

>>> unq[:5]
array([[  0,  82,  78],
       [  6, 221, 188],
       [  9, 209,  85],
       [ 14, 210,  24],
       [ 14, 254,  88]], dtype=uint8)
>>> unq_cnts[:5]
array([1, 1, 1, 1, 1], dtype=int64)

答案 1 :(得分:2)

这是我的解决方案:

  • 使用dtype = uint32
  • 将图像转换为单维数组
  • sort()数组
  • 使用diff()查找颜色发生变化的所有位置。
  • 再次使用diff()查找每种颜色的计数。

代码:

In [50]:
from collections import defaultdict
import cv2
import numpy as np
img = cv2.imread("test.jpg")

In [51]:
%%time
counts = defaultdict(int)
for row in img:
    for val in row:
        counts[tuple(val)] += 1
Wall time: 1.29 s

In [53]:
%%time
img2 = np.concatenate((img, np.zeros_like(img[:, :, :1])), axis=2).view(np.uint32).ravel()
img2.sort()
pos = np.r_[0, np.where(np.diff(img2) != 0)[0] + 1]
count = np.r_[np.diff(pos), len(img2) - pos[-1]]
r, g, b, _ = img2[pos].view(np.uint8).reshape(-1, 4).T
colors = zip(r, g, b)
result = dict(zip(colors, count))
Wall time: 177 ms

In [49]:
counts == result
Out[49]:
True

如果你可以使用pandas,你可以调用pandas.value_counts(),它是用cython实现的 用哈希表。