Skip to content

Instantly share code, notes, and snippets.

@ankane
Last active September 12, 2019 01:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankane/33ffa59ea0f5add37edee04fa7aacd9e to your computer and use it in GitHub Desktop.
Save ankane/33ffa59ea0f5add37edee04fa7aacd9e to your computer and use it in GitHub Desktop.
require "onnxruntime"
require "mini_magick"
require "numo/narray"
img = MiniMagick::Image.open("images/32576677167_a066c5a7aa_z.jpg")
img.resize "448x448^", "-gravity", "center", "-extent", "448x448"
pixels = Numo::NArray[*img.get_pixels]
pixels = pixels.transpose(2, 0, 1)
pixels = pixels.expand_dims(0)
model = OnnxRuntime::Model.new("rain_princess.onnx")
result = model.predict(input1: pixels.to_a)
out_pixels = Numo::NArray[*result["output1"].first]
out_pixels = out_pixels.clip(0, 255)
out_pixels = out_pixels.transpose(1, 2, 0).cast_to(Numo::UInt8)
img = MiniMagick::Image.import_pixels(out_pixels.to_binary, img.width, img.height, 8, "rgb", "jpg")
img.write("output.jpg")
@kojix2
Copy link

kojix2 commented Sep 12, 2019

The following line is easy to understand,

blob = out_pixels.to_a.flatten.pack("C*")

But you can also write like this.

blog = out_pixels.to_string
blog = out_pixels.to_binary

That's the good part of Numo::UInt8.

@ankane
Copy link
Author

ankane commented Sep 12, 2019

Awesome, much more readable - didn't know that existed. Will update the post and gist. Thanks @kojix2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment