简体   繁体   English

为numpy数组添加噪音的最快方法

[英]Fastest way to add noise to a numpy array

I have a numpy.ndarray that represents an image and I would like to add random noise to it. 我有一个numpy.ndarray代表一个图像,我想添加随机噪音。 I've done some tests and so far the fastest solution I have is to do: 我做了一些测试,到目前为止,我所做的最快的解决方案是:

def RandomNoise(x):
    x += np.random.random(x.shape)

But when I have big images/arrays, this solution is still really too slow. 但是当我有大图像/数组时,这个解决方案仍然太慢了。 What is the fastest way to do it? 最快的方法是什么?

The easiest way to make this faster is to avoid allocating the random array which you don't actually need. 使速度更快的最简单方法是避免分配实际上不需要的随机数组。 To avoid that, use Numba: 为避免这种情况,请使用Numba:

import numba
import random

@numba.njit
def RandomNoise2(x):
    x = x.reshape(-1) # flat view
    for ii in range(len(x)):
        x[ii] += random.random()

For moderate-size arrays like 4 million elements, this is slightly faster after the first run when it JIT-compiles the code. 对于像400万个元素这样的中等大小的数组,在JIT编译代码的第一次运行后,这稍微快一些。 For larger arrays like 20 million values it is twice as fast, or more. 对于像2000万个值这样的大型数组,它的速度提高了两倍甚至更多。 If you're low on memory it will be massively faster, because it will avoid swapping. 如果你的内存不足,它会大大加快,因为它会避免交换。

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

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