logo

How to Load Images in Julia and Save Them as Matrices 📂Julia

How to Load Images in Julia and Save Them as Matrices

Code

using Images

cd("C:/Users/rmsms/OneDrive/examples")
pwd()

example = load("example.jpg")
typeof(example)
size(example)

gray1 = Gray.(example)
typeof(gray1)
size(gray1)

M = convert(Array{Float64},gray1)
typeof(M)
size(M)
colorview(Gray, M.^(1/2))

save("rgb.png", colorview(RGB, example))
save("gray1.png", colorview(Gray, gray1))
save("gray2.png", colorview(Gray, transpose(gray1)))
save("gray3.png", colorview(Gray, M.^(1/2)))

Let’s briefly understand the example code from top to bottom:

  • cd() : Change Directory, changes the working directory to the desired location.

  • pwd() : Print Working Directory, prints the working directory. If you want to follow the example exactly, download the above file to your working directory and rename it to example.jpg.

example.jpg

20191213\_185204.png

  • load() : Loads an image file in the working directory. The type of the loaded image is Array{RGB{Normed{UInt8,8}},2}. This is slightly different from other languages where a color image is represented by a tensor by combining three matrices. In fact, such an approach has caused a lot of confusion due to the lack of a unified standard across color spaces and libraries. Julia instead uses a single type and understands it as a two-dimensional array for width and height. The image is printed on the Plot panel the moment it is loaded. 20191213\_184951.png

  • Gray() : Used to convert the image to grayscale. It is important to note that what is actually used is not Gray() but Gray.(). This indicates that the function itself converts a single pixel to grayscale, and putting a dot applies it to all pixels.

  • size() : Returns the size of the image. As mentioned, it does not treat color and grayscale as tensors of different shapes but as arrays of the same size with different data types. 20191213\_185608.png

  • Convert() : Converted the gray1 image into Array{Float64}, i.e., a matrix. Thus, 0 represents black and 1 represents white in the matrix used to express the grayscale image.

  • colorview() : This function itself is used to print images or matrices. There’s no need to convert the matrix back into an image as one can directly check the image on the Plot panel. In the example code, the square root of each element of the matrix $M$ was taken. Since all elements of the matrix belong to $[0,1]$, this transformation corresponds to generally brightening the image. 20191213\_190355.png 20191213\_190404.png

  • save() : Saves the images in the working directory:gray1.png : Saved in grayscale.gray2.png : Saved in grayscale and in the transpose matrix state.gray3.png : Saved in grayscale and in a brightened state.rgb.png : Saved with the original colors.

Environment

  • OS: Windows
  • julia: v1.5.0