# Rewriting Python code using Images.jl

**URL:** <https://discourse.julialang.org/t/rewriting-python-code-using-images-jl/37323>\
**Category:** General Usage\
**Tags:** question, images, python\
**Created:** [April 10, 2020, 10:13am UTC](https://discourse.julialang.org/t/rewriting-python-code-using-images-jl/37323 "2020-04-10T10:13:27Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Christian](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/christian/32/9994_2.png) [@Christian](https://discourse.julialang.org/u/Christian)\
**Post date:** [April 10, 2020, 10:13am UTC](https://discourse.julialang.org/t/rewriting-python-code-using-images-jl/37323/1 "2020-04-10T10:13:27Z")

</div>

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:

```nohighlight
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:

```julia
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?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [April 10, 2020, 3:01pm UTC](https://discourse.julialang.org/t/rewriting-python-code-using-images-jl/37323/2 "2020-04-10T15:01:32Z")

</div>

> [@Christian](#):
>
> 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.

```julia
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](https://github.com/JuliaArrays/ElasticArrays.jl) to do this from the start.

---

<div class="post-metadata">

**Author:** ![Christian](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/christian/32/9994_2.png) [@Christian](https://discourse.julialang.org/u/Christian)\
**Post date:** [April 10, 2020, 5:38pm UTC](https://discourse.julialang.org/t/rewriting-python-code-using-images-jl/37323/3 "2020-04-10T17:38:10Z")

</div>

Very helpful. Thank you!
