Home > front end >  How to load a png image as an array in Julia?
How to load a png image as an array in Julia?

Time:11-19

How can I load a png as an array using Julia? I have a 256X256 image and I would like to load it as a 256X256 float array.

I tried using Images

using Images

img = load("pic.png")

however this merely loads and plots the image and I am not able to extract pixel values.

Additionally, I have tried

img = read("pic.png")

but this loads all the values into a vector. In theory I can reshape the vector to make it 256X256, but I was hoping for something that could work without me having to know the shape of the image ahead of time.

Lastly, if I load PyPlot I can load the image exactly how I want

import PyPlot as plt

img = plt.imread("pic.png")

however I would ideally like to be able to load the image with without invoking PyCall and.

CodePudding user response:

The recommended approach is to use FileIO. FileIO will choose appropiate parser (could be ImageMagick but for png it will be raher PNGFiles.jl instead). This provides you a common central interface for accessing images.

Note that this approach is also recommended on the ImageMagick.jl GitHub page

julia> using FileIO

julia> img = FileIO.load("c:\\temp\\fig.png")
288×432 Array{RGBA{N0f8},2} with eltype ColorTypes.RGBA{FixedPointNumbers.N0f8}:
 RGBA{N0f8}(1.0,1.0,1.0,0.0)  …  RGBA{N0f8}(1.0,1.0,1.0,0.0)
 RGBA{N0f8}(1.0,1.0,1.0,0.0)     RGBA{N0f8}(1.0,1.0,1.0,0.0)
 ⋮                            ⋱
 RGBA{N0f8}(1.0,1.0,1.0,0.0)  …  RGBA{N0f8}(1.0,1.0,1.0,0.0)
 RGBA{N0f8}(1.0,1.0,1.0,0.0)     RGBA{N0f8}(1.0,1.0,1.0,0.0)

If you want this as a 3 dimensional Array you need to be using Images and try channelview:

julia> imgarr = channelview(img)
4×288×432 reinterpret(reshape, N0f8, ::Array{RGBA{N0f8},2}) with eltype N0f8:
[:, :, 1] =
 1.0  1.0  1.0  1.0  1.0  1.0  …  1.0  1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0  1.0  1.0     1.0  1.0  1.0  1.0  1.0
...

If you want a different order of dimensions this can be further combined with permutedims(imgarr, [2,3,1])

  • Related