简体   繁体   English

将向量的numpy数组映射到字典

[英]Mapping numpy array of vectors to dictionary

I'm trying to map a color histogram where each pixel also as another (float) property, alpha, from a similar size array. 我正在尝试映射一个颜色直方图,其中每个像素也来自相似大小数组的另一个(浮动)属性alpha。 I want eventually to have a dictionary of (color) -> (count, sum) where count is actually the histogram count for that color, and sum is the sum of alpha values that correspond to a certain color. 我最终希望拥有一个(color)->(count,sum)的字典,其中count实际上是该颜色的直方图计数,而sum是对应于某种颜色的alpha值的总和。

here's a simple python code that makes what i want (c and d are the same length, and are very long): 这是使我想要的简单的python代码(c和d的长度相同,并且非常长):

for i in range(len(c)):
        if str(c[i]) in dict:
            dict[str(c[i])][0] += 1
            dict[str(c[i])][1] += alpha[i]
        else:
            dict[str(c[i])] = [0, alpha[i]]

but naturally that takes a lot of time. 但是自然会花费很多时间。 Any ideas for a numpy equivalent? 对麻木等效的任何想法?

Thanks 谢谢

Okay, so i eventually found a very nice solution using this answer using only numpy: https://stackoverflow.com/a/8732260/1752591 好的,所以我最终仅使用numpy使用此答案找到了一个非常好的解决方案: https : //stackoverflow.com/a/8732260/1752591

Which is a function that sums up vector according to another vector of indices. 这是根据另一个索引向量对向量求和的函数。 So all I had to do is to give an id for each color, and make the dictionary: 因此,我要做的就是为每种颜色指定一个ID,然后制作字典:

d = alpha.reshape((-1))
id = color_code_image(colormap)

v, g = sum_by_group(d, id)
count, g = sum_by_group(np.ones(len(d)), id)
avg = v/count

return dict(np.array([g, avg]).T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM