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

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

问题描述

我必须计算矩阵(二维数组)中大于 200 的所有值.

我为此写的代码是:

za=0p31 = numpy.asarray(o31)对于范围内的 i(o31.size[0]):对于范围内的 j(o32.size[1]):如果 p31[i,j]<200:za=za+1印扎

o31 是一个图像,我将其转换为矩阵,然后找到值.

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

解决方案

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

直接使用 numpy.where 将产生一个布尔掩码,指示某些值是否符合您的条件:

<预><代码>>>>数据数组([[1, 8],[3, 4]])>>>numpy.where( 数据 > 3 )(数组([0, 1]), 数组([1, 1]))

并且可以使用掩码直接索引数组以获取实际值:

<预><代码>>>>数据[ numpy.where( 数据> 3 ) ]数组([8, 4])

您从那里获取它的确切位置将取决于您希望结果的形式.

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

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 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?

解决方案

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.

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天全站免登陆