Home > Enterprise >  Image Analysis Gaussian Filter Optimization and Speedup
Image Analysis Gaussian Filter Optimization and Speedup

Time:01-05

I'm looking for a way to speed up the following code. This code block is a simplified version of an image analysis pipeline I've developed, but the main structure is there. I do need the gaussian filter. Since it's a source that's outside of my control, I've decided to leave it in the example.

In the stack definition, I've included the size of the images I'm using. They are approximately 200 frames whose resolution is 1024, 512.

Is there a way to speed this up with Python?

import numpy as np
import time
from scipy import ndimage as ndi
 
def gauss(stack):
    for i in range(stack.shape[0]):
        stack[i,:,:] -= ndi.gaussian_filter(stack[i, :, :], 10)
    return stack

stack = np.random.randint(0, 20, size=(200,1024,512))
t = time.time()
gs = gauss(stack)
print(f"{time.time() - t:0.3f} seconds")

CodePudding user response:

If you do not mind losing a little of "precision" (you may not notice difference), you can use truncate parameter (default is 4.0) of the gaussian filter, for example to truncate to 2 sigmas (at least to 3).

import numpy as np
import time
from scipy import ndimage as ndi


def gauss(stack, truncate):
    for i in range(stack.shape[0]):
        stack[i, :, :] -= ndi.gaussian_filter(stack[i, :, :], 10, truncate=truncate)
    return stack


for truncate in [4, 3, 2]:
    stack = np.random.randint(0, 20, size=(200, 1024, 512))
    t = time.time()
    gs = gauss(stack, truncate=truncate)
    print(f"truncate {truncate}: {time.time() - t:0.3f} seconds")
truncate 4: 8.462 seconds
truncate 3: 6.021 seconds
truncate 2: 4.257 seconds
  • Related