Skip to content

Instantly share code, notes, and snippets.

@stocks29
Created November 28, 2024 16:58
Show Gist options
  • Save stocks29/4f51df8a1e0dce46505f770faf83fb1d to your computer and use it in GitHub Desktop.
Save stocks29/4f51df8a1e0dce46505f770faf83fb1d to your computer and use it in GitHub Desktop.
NxImage Resize Memory

NxImage Resize Memory

Mix.install(
  [
    {:exla, "~> 0.9.2"},
    {:nx, "~> 0.9.2"},
    {:nx_image, "~> 0.1.2"},
    {:req, "~> 0.5.7"},
    {:stb_image, "~> 0.6.9"}
  ],
  config: [
    config: [nx: [default_backend: EXLA.Backend]]
  ]
)

Section

get_process_memory = fn ->
  pid = System.pid()
  cmd = "ps -o rss= -p #{pid}"
  result = :os.cmd(to_charlist(cmd))
  case Integer.parse(to_string(result)) do
    {value, _} -> value
    :error -> :unknown
  end
end
#Function<43.39164016/0 in :erl_eval.expr/6>
img_url = "https://i.swncdn.com/media/950w/via/5333-thanksgiving.jpg"
%{status: 200, body: image_data} = Req.get!(img_url)

tensor = 
  image_data
  |> StbImage.read_binary!()
  |> StbImage.to_nx()
#Nx.Tensor<
  u8[height: 496][width: 950][channels: 3]
  [
    [
      [131, 85, 0],
      [133, 86, 0],
      [139, 89, 4],
      [149, 97, 14],
      [150, 95, 15],
      [133, 76, 0],
      [124, 64, 0],
      [135, 73, 0],
      [177, 113, 42],
      [164, 97, 29],
      [133, 64, 0],
      [124, 52, 0],
      [131, 51, 0],
      [135, 51, 5],
      [143, 55, 15],
      [136, 51, 10],
      [137, 59, ...],
      ...
    ],
    ...
  ]
>
Enum.each(1..2, fn _ ->
  memory = get_process_memory.()
  IO.puts("memory before resize: #{memory} KB")
  
  NxImage.resize(tensor, {224, 224})
  
  memory = get_process_memory.()
  IO.puts("memory after resize: #{memory} KB")
end)
memory before resize: 197792 KB
memory after resize: 227392 KB
memory before resize: 227392 KB
memory after resize: 231648 KB
:ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment