Nikki
Nikki

Reputation: 195

How to optimize for loops for generating a new random Poisson array in python?

I want to read an grayscale image, say something with (248, 480, 3) shape, then use each element of it as the lam value for making a Poisson random value and do this for each element and make a new data set with the same shape. I want to do this as much as nscan, then I want to add them all together and put them in a new data set and plot it again to get something that is similar to the first image that I put in the beginning. This code is working but it is extremely slow, I was wondering if there is any way to make it faster?

import numpy as np
import matplotlib.pyplot as plt

my_image = plt.imread('myimage.png')


def genP(data):

    new_data = np.zeros(data.shape)

    for i in range(data.shape[0]):

        for j in range(data.shape[1]):

            for k in range(data.shape[2]):

                new_data[i, j, k] = np.random.poisson(lam = data[i, j, k])


    return new_data        



def get_total(data, nscan = 1):

    total = genP(data)

    for i in range(nscan):

        total += genP(data)

    total = total/nscan


    plt.imshow(total)
    plt.show()


get_total(my_image, 100) 

Upvotes: 2

Views: 185

Answers (1)

Aaron
Aaron

Reputation: 11075

numpy.random.poisson can entirely replace your genP() function... This is basically guaranteed to be much faster.

If size is None (default), a single value is returned if lam is a scalar. Otherwise, np.array(lam).size samples are drawn

def get_total(data, nscan = 1):
    total = np.random.poisson(lam=data)
    for i in range(nscan):
        total += np.random.poisson(lam=data)
    total = total/nscan
    plt.imshow(total)
    plt.show()

Upvotes: 1

Related Questions