Python Forum

Full Version: Optimisation problem - star identification
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone

I have written a comet finding program however I find it runs a bit slow for my liking. I have been able to speed it up by using numba (compiler) but I probably can optimise the program further with some better coding. Your help in speeding these loops up would be appreciated.

Here is my code

def points(file):

# routine to find stars in a 1024 x 1024 pixel image stored as an array in imgarray (an array) 

    pnts=[]

# get file and read into array

    fileext="/archive/" + date + "/" + file 
    imgarray = ndimage.imread(fileext)
    

#Loop through all pixels excluding some defined areas I don't want to search
       
    for j in range(18,512):
        for i in range(18,512):
            
            if 345<j<512 and 363<i<512:
                continue
            
            if 380<j<512 and 320<i<363:
                continue
            if 300<j<346 and 400<i<512:
                continue

            if (i+j)<100:
                continue
            
# img[x,y,0] is the value of the pixel 
# sum 8 pixels which are 2 pixels from my target pixel and then take an average of that figure which is stored in a
           
            a=((int(imgarray[(i-2),(j-2),0])+int(imgarray[(i-2),(j+2),0])+int(imgarray[(i-2),j,0])+int(imgarray[(i+2),(j-2),0])+int(imgarray[(i+2),(j+2),0])+int(imgarray[(i+2),j,0])+int(imgarray[i,(j+2),0])+int(imgarray[i,(j-2),0]))/8)


# if the pixel location is below a certain level of brightness we don't want it so continue on to next pixel 
                
            if imgarray[i,j,0]<160:
                continue

# if the brightness of the selected pixel is more than 30 greater than the average stored in a stored that pixel's location in t and then append to pnts which is a list of points which I think are stars in the image.            
            
            if ((imgarray[i,j,0]-a)) >30:
                t=[j,i]
                pnts.append(t)
        
    return(pnts)    


Can anyone suggest a better way to write this code so that it runs faster. I had a look at numpy but couldn't find anything that would work for my code.

cheers Peter
Did you look at scikit-image package? Your problem could be likely presented in vectorized form, e.g. You can apply averaging to entire image, e.g.

from skimage.filters.rank import mean
import numpy as np
aux_result = mean(your_image, np.array([[1,1,1],[1,0,1],[1,1,1]])) # intermediate result; chose appropriate mask;
Further, you can restore values for certain pixels, e.g.
aux_result[your_image > threshold] = your_image[your_image > threshold]
You need to restructure this code for your needs, though.

Also, you can significantly increase calculation speed, if you rewrite loops in Cython.