Most idomatic way to convert an Images.jl Image to a 3-d array?

I’ve loaded an image file to get a 2-d array of RGB color values. What I want is a 3-d array with depth 3.

The function below will do the job. But is there a more idomatic way?

rgb_to_array(img) = begin
    H, W = height(img), width(img)
    a = zeros(H, W, 3)
    for w in 1:W
        for h in 1:H
            rgb = img[h,w]
            a[h,w,1] = rgb.r
            a[h,w,2] = rgb.g
            a[h,w,3] = rgb.b
        end
    end
    a
end

I think this should do the job:
permutedims(reinterpret(eltype(eltype(img)), img), (2, 3, 1))

Check out channelview(): http://juliaimages.github.io/latest/quickstart.html#Colors,-the-0-to-1-intensity-scale,-and-views-1

1 Like
permutedims(channelview(img), (2,3,1))
2 Likes

note that the permutedims is only needed because you seem to want the color channel to be in the last dimension.

1 Like

Awesome. Thanks!

Hi! i have problem manipulating 3-D image.
I want to save a 3-D array of image (m, n, 3) in png format. I tried some functions and they gave me errors.

Thank you in advance who can help.