【问题标题】:Occurrence of list in ndarray [duplicate]ndarray中列表的出现[重复]
【发布时间】:2019-11-13 21:32:12
【问题描述】:

我有一个 RGB 图像 -ndarray-,我想计算此图像中某些颜色的出现次数,例如 [255,0,0] 或 [0,0,255]。

图像数据示例

np.ones((3, 3, 3)) * 255

array([[[255., 255., 255.],
        [255., 255., 255.],
        [255., 255., 255.]],
       [[255., 255., 255.],
        [255., 255., 255.],
        [255., 255., 255.]],
       [[255., 255., 255.],
        [255., 255., 255.],
        [255., 255., 255.]]])

所以我想要这样的东西

{
'[255,255,255]' : 9,
}

【问题讨论】:

  • 我添加了一个例子。所以一般RGB图像的尺寸是(宽,高,3)
  • np.unique 可用于链接的欺骗 @MatteoPeluso 作为一维数组。但是,使用 2darray 会更棘手:)

标签: python numpy image-processing numpy-ndarray


【解决方案1】:

一个解决方案可能是Counter 函数:

from collections import Counter
import numpy as np

# Generate some data
data = np.ones((10, 20, 3)) * 255

# Convert to tuple list
data_tuple = [ tuple(x) for x in data.reshape(-1,3)]
Counter(data_tuple)

返回:

Counter({(255.0, 255.0, 255.0): 200})

【讨论】:

  • 感谢您的回答。它工作得很好,但需要很长时间
【解决方案2】:

虽然可以使用Counteropencv histogram function 来计算每个像素的频率,但对于特定像素,使用它更有效:

import numpy as np

ar = np.ones([3,3,3]) *255
ar[1,1,:] = [0, 0, 200]

pixels = dict()
pixels['[255, 255, 255]'] =  np.sum(np.all(ar == [255,255, 255], axis = 2))
pixels['[0, 0, 200]'] =  np.sum(np.all(ar == [0, 0, 200], axis = 2)) 

结果:{'[255, 255, 255]': 8, '[0, 0, 200]': 1}

【讨论】:

    【解决方案3】:

    这是一种使用NumPy 的方法。作为 0-255 范围内的值,我们可以将行视为具有 f8 类型的三个元素的元组,并使用 np.unique 来计算原始 ndarray 中实际行的出现次数。使用 nakor 的数组:

    a = np.ones((10, 20, 3)) * 255
    

    我们可以这样做:

    vals, counts = np.unique(a.view('f8,f8,f8'), return_counts=True)
    

    地点:

    print(vals)
    array([(255., 255., 255.)],
          dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8')])
    
    print(counts)
    array([200])
    

    【讨论】:

    • 我尝试了一张真实的图片,但我遇到了这个错误ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.
    猜你喜欢
    • 2021-05-25
    • 2021-07-16
    • 2013-07-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多