How to make this custom median for color images faster

I have made custom median filter for color images, but it performs slow and takes high memory compared to OpenCV.medianBlur. Here is code

using ImageIO
using FileIO
using ImageFiltering
using ImageCore
# using Statistics
using OpenCV
using BenchmarkTools

function median_filter(img, ksize::Tuple{Int64,Int64}=(3, 3))
    # mapwindow(median!, img, ksize)
    mapwindow(ImageFiltering.MapWindow.median_fast!, img, ksize)
end

function color_median_filter(img, ksize::Tuple{Int64,Int64}=(3, 3))
    cview_img = channelview(img)
    s::Tuple{Int64,Int64,Int64} = size(cview_img)
    filtered_image::Array{N0f8,3} = zeros(N0f8, s)
    for idx in 1:s[1]
        filtered_image[idx, :, :] = median_filter(cview_img[idx, :, :], ksize)
    end
    colorview(RGB, filtered_image)
end

noisy_img_path = "lighthouse_noisy.png"

lighthouse_noisy_cv = OpenCV.imread(noisy_img_path)
lighthouse_noisy = load(noisy_img_path)

s1 = 3
s2 = (3, 3)
julia> @benchmark OpenCV.medianBlur($(lighthouse_noisy_cv), $(s1))
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
 Range (min … max):  423.100 μs …  1.064 ms  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     460.600 μs              ┊ GC (median):    0.00%
 Time  (mean ± σ):   476.162 μs ± 48.744 μs  ┊ GC (mean ± σ):  0.00% ± 0.00%

       █▅▂▄▇▃
  ▁▂▃▃▆███████▅▄▄▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▁▂▁▁▂▁▁▁▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▂
  423 μs          Histogram: frequency by time          663 μs <

 Memory estimate: 1.05 KiB, allocs estimate: 37.

julia> @benchmark color_median_filter($lighthouse_noisy, $s2)
BenchmarkTools.Trial: 41 samples with 1 evaluation.
 Range (min … max):  118.774 ms … 134.163 ms  ┊ GC (min … max): 0.00% … 3.73%
 Time  (median):     121.594 ms               ┊ GC (median):    0.00%
 Time  (mean ± σ):   122.864 ms ±   3.296 ms  ┊ GC (mean ± σ):  0.94% ± 1.53%

      ▁   ▁█
  ▄▄▄▄█▄▄▁██▇▇▁▁▇▇▄▄▁▄▄▁▄▁▁▇▇▁▄▁▁▁▁▇▁▁▁▁▁▄▁▁▁▁▁▁▁▁▄▁▁▁▁▁▁▁▁▁▁▁▄ ▁
  119 ms           Histogram: frequency by time          134 ms <

 Memory estimate: 12.37 MiB, allocs estimate: 107429.

Both filters remove noise from original image. Noisy image created using below code

using Noise
using TestImages
using Images

test_img = testimage("lighthouse")
save("lighthouse_noisy.png", salt_pepper(test_img))

Julia version information

Julia Version 1.9.3
Commit bed2cd540a (2023-08-24 14:43 UTC)
Build Info:
  Official https://julialang.org/ release
Platform Info:
  OS: Windows (x86_64-w64-mingw32)
  CPU: 16 × AMD Ryzen 7 PRO 5850U with Radeon Graphics
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-14.0.6 (ORCJIT, znver3)
  Threads: 1 on 16 virtual cores

Thanks

I believe there are packages with efficient median filters already. Try to search JuliaHub.

@profview show 62% spent in partialsort!