Faster image pixel manipulation in python

946 Views Asked by At

I have the following nested loop which goes over a big image (7020x5100) and sets pixel values of another image with the same dimension depending of the value of i. The problem that this is very very slow...could you please give a hint, how to speed up this algorithm?

A=[]

for x in xrange(x_img):
    for y in xrange(y_img):
        A.append(probImage1[x][y])
        A.append(probImage2[x][y])
        A.append(probImage3[x][y])
        i = np.argmax(A)
        if i == 0:
            processedImage[x,y] = [1, 89, 255]
        if i == 1:
            processedImage[x,y] = [241, 28, 3]
        if i == 2:
            processedImage[x,y] = [137, 254, 255]
        A = [] 
1

There are 1 best solutions below

0
docPhil On

On my machine your method takes 6 mins 55 seconds!

Try to avoid for loops iterating over an image, especially with all memory allocation going on. This method takes 2.14 seconds for a 7020 x 5100 image

newProb=np.dstack((probImage1,probImage2,probImage3))
A=np.argmax(newProb,axis=2)
processedImage[A==0]=[1,89,255]
processedImage[A==1]=[241,28,3]
processedImage[A==2]=[137,254,255]