Fastest way to add noise to a numpy array

2.9k Views Asked by At

I have a numpy.ndarray that represents an image and I would like to add random noise to it. 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?

1

There are 1 best solutions below

5
On

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:

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. For larger arrays like 20 million values it is twice as fast, or more. If you're low on memory it will be massively faster, because it will avoid swapping.