Rewriting Python code using Images.jl

Hello,
I’m trying to convert some Python to Julia but I’m having an issue with the following lines.

The code takes an array of gradients (all with nxm dims) and returns the median gradient (in nxm dims).
In Python the relevant code looks like this:

import cv2
import numpy as np

gradx = [cv2.Sobel(img, (cv2.CV_64F), 1, 0, ksize=3) for img in images]
medx = np.median(np.array(gradx), axis=0)

In Julia I have the following so far:

using Images
gradx = []

for img in images
    gx,gy = imgradients(collect(img), KernelFactors.sobel, "replicate")
    push!(gradx,gx)
end

medx = ??

Is it possible to write the above code using list comprehensions? Also, is there a function to find the median gradient, like the one provided by numpy?

There is the function median in the Statistics package, e.g.

using Statistics
medx = [median(g[i,j] for g in gradx) for i in 1:nx, j in 1:ny]

However, it would be faster if you first convert your array-of-arrays gradx to a multidimensional array. You can use e.g. the ElasticArrays package to do this from the start.

1 Like

Very helpful. Thank you!