算以矩阵大于某个值的所有值 [英] Count all values in a matrix greater than a value

查看:205
本文介绍了算以矩阵大于某个值的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我都数不过来的所有值矩阵(2-D数组)是大于200。

I have to count all the values in a matrix (2-d array) that are greater than 200.

在code我写下来是这样的:

The code I wrote down for this is:

za=0   
p31 = numpy.asarray(o31)   
for i in range(o31.size[0]):   
    for j in range(o32.size[1]):   
        if p31[i,j]<200:   
            za=za+1   
print za

O31 是一个形象,我把它转换成一个矩阵,然后找到值。

o31 is an image and I am converting it into a matrix and then finding the values.

我的问题是,有没有简单的方法来做到这一点?

My question is, is there a simpler way to do this?

推荐答案

numpy.where 函数是你的朋友。因为它的实施,以充分利用数组类型的,对于大型的图像,你应该注意到了您提供的纯Python解决方案的速度提升。

The numpy.where function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.

使用numpy.where直接将产生一个布尔面膜一定的指示值是否符合您的条件:

Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:

>>> data
array([[1, 8],
       [3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))

和掩模,可以直接使用索引数组,得到的实际值:

And the mask can be used to index the array directly to get the actual values:

>>> data[ numpy.where( data > 3 ) ]
array([8, 4])

正是你从那里将取决于你想要什么样的形式在结果中。

Exactly where you take it from there will depend on what form you'd like the results in.

这篇关于算以矩阵大于某个值的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆