Machine Learning in Elixir B1, page 55. cannot open image

@seanmor5

I want to invert the cat image. Therefore I downloaded the file in the same folder as the livemd file for chapter 03 I created.
I use the code:

 "Cat.jpg" |> StbImage.read_file!() |> StbImage.resize(256, 256) |> Nx.dot(invert_color_channels) |> Nx.as_type({:u, 8}) |> Kino.Image.new() 

returns:

** (ArgumentError) could not open file
(stb_image 0.6.2) lib/stb_image.ex:247: StbImage.read_file!/2
/path_to_folder/ch03_harness_the_power_of_math.livemd#cell:4r2dpa25qaotbzseednwllnwqlrrvd6l:8: (file)

Hope you can help me out here.

Hey @sehHeiden,

That’s because StbImage.read_file!() expects an absolute path to the image file.

# Expects StbImage.read_file!("/path/to/Cat.jpg") 

Assuming it’s in the same folder as your Livebook .livemd, we’ll need to figure out the current directory relative to your .livemd & image are in.

We do that via the following:

  • __DIR__: Returns the absolute path of the directory of the current file as a binary.
  • Path.join: Joins two paths.

Putting it together

__DIR__ |> Path.join("Cat.jpg") |> StbImage.read_file!() |> StbImage.resize(256, 256) |> StbImage.to_nx() |> Nx.dot(invert_color_channels) |> Nx.as_type({:u, 8}) |> Kino.Image.new() 

That should locate the file correctly & invert the image:

Hope it helps!

I assume my problem was, that I thought my local folder is where the livemd file is in, but It seems, its the folder from which the shell starts the livebook programme.

Thank you Shawn this was very helpful. Can you please point me in the right direction as well? I followed your modifications but what I get back looks more like this:

Any idea what I am doing incorrectly? I tried running

StbImage.read_file!(channels: 3)

as well but it only changed the colors of the bars.

Code as text to enable copy/paste:

invert_color_channels = Nx.tensor([ [-1, 0, 0], [0, -1, 0], [0, 0, -1] ]) __DIR__ |> Path.join("Cat.jpg") |> StbImage.read_file!() |> StbImage.resize(256, 256) |> StbImage.to_nx() |> Nx.dot(invert_color_channels) |> Nx.as_type({:u, 8}) |> Kino.Image.new()