更换已经比一些值的Python的numpy的阵列中的所有元素 [英] Replace all elements of Python NumPy Array that are greater than some value

查看:329
本文介绍了更换已经比一些值的Python的numpy的阵列中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D numpy的阵列,并想以255.0替换所有值在它大于或等于一个阈值T。据我所知,最根本的办法是:

 形状= arr.shape
结果= np.zeros(形状)
对于在范围X(0,形状[0]):
    对于在范围Y(0,形状[1]):
        如果ARR [X,Y]> = T:
            结果[X,Y] = 255


  1. 什么是做到这一点的最简洁和Python的方式?


  2. 有一个更快的(可能不够简明和/或更少的Python化)的方式来做到这一点?


这将是一个窗口/级别调整子程序用于人体头部的MRI扫描的一部分。二维数组numpy的是图像的像素数据。


解决方案

我认为既要做到这一点,最快,最简洁的方法是使用numpy的的内置索引。如果你有一个 ndarray 名为改编可以取代所有元素> 255 用值 X 如下:

 改编[ARR> 255] = X

我和一个500×500随机矩阵跑这在我的机器上,替换所有值> 0.5与5,并花了7.59ms平均。

 在[1]:进口numpy的为NP
[2]:A = np.random.rand(500,500)
[3]:timeit A [A> 0.5] = 5
100圈,最好的3:每循环7.59毫秒

I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be:

shape = arr.shape
result = np.zeros(shape)
for x in range(0, shape[0]):
    for y in range(0, shape[1]):
        if arr[x, y] >= T:
            result[x, y] = 255

  1. What is the most concise and pythonic way to do this?

  2. Is there a faster (possibly less concise and/or less pythonic) way to do this?

This will be part of a window/level adjustment subroutine for MRI scans of the human head. The 2D numpy array is the image pixel data.

解决方案

I think both the fastest and most concise way to do this is to use Numpy's builtin indexing. If you have a ndarray named arr you can replace all elements >255 with a value x as follows:

arr[arr > 255] = x

I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.

In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop

这篇关于更换已经比一些值的Python的numpy的阵列中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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