bionanoimaging / FourierTools.jl

Tools for working with Fourier space.
https://bionanoimaging.github.io/FourierTools.jl/stable/
MIT License
56 stars 6 forks source link

Gaussian Filtering doesn't work for zeros #45

Closed sebaseb98 closed 1 month ago

sebaseb98 commented 1 month ago

the code filter_gaussian(zeros(5)) returns [NaN, NaN, NaN, NaN, NaN].

Not that it is too important to be able to filter zero arrays, but in my case I want to filter images column-wise and it could happen to have columns of zeros. For such cases I would prefer the package to return the correct result rather than work around this bug. When I looked into the code, I found that the division by the sum might cause the error (its line 315 in src/fourier_filtering.jl) or line 5 in the following snippet.

function filter_gaussian!(arr, sigma=eltype(arr)(1); real_space_kernel=true, border_in=(real(eltype(arr)))(0), border_out=(real(eltype(arr))).(2 ./ (pi .* sigma)), kwargs...)
    if real_space_kernel
        mysum = sum(arr)
        fourier_filter!(arr, gaussian; transform_win=true, sigma=sigma, kwargs...)
        arr .*= (mysum/sum(arr))
        return arr
    else
        return fourier_filter!(arr; border_in=border_in, border_out=border_out, kwargs...)
    end
end

For this particular case a short check that sum(arr) != 0 should do the job, but I am not sure how this fits in the philosophy of the whole package and if there are functions having the same problems

RainerHeintzmann commented 1 month ago

Thanks a lot for picking this up. The error actually goes a bit deeper. Using the sum of the data is just not the right way to normalize it. E.g. an array can be zero integral also by containing positive and negative values. I thus shifted the (optional) normalization to the kernel and introduced an optional argument, which seems more sensible. Such a normalization is advantageous for real-space Gaussians which are first transformed and then used for filtering. This is the preferred mode for small kernel sizes. Here is the pull request.

roflmaostc commented 1 month ago

I tagged 0.4.6 So please update your package after it got merged https://github.com/bionanoimaging/FourierTools.jl/commit/3697e743847d7806ae8fff3f2d62b6adcf2ec9d5