Skip to content

Instantly share code, notes, and snippets.

@zacky1972
Last active December 18, 2023 07:02
Show Gist options
  • Save zacky1972/7777c34c89ae797c581a946c08cba6c4 to your computer and use it in GitHub Desktop.
Save zacky1972/7777c34c89ae797c581a946c08cba6c4 to your computer and use it in GitHub Desktop.
Horizontal image division
# Setting for Evision to use precompiled version
System.put_env("EVISION_PREFER_PRECOMPILED", "true") # Remove if you use a platform on which Evision does not provide a pre-compiled library.
System.put_env("EVISION_PRECOMPILED_CACHE_DIR", "#{System.user_home!()}/.cache")
# Setting integration of Nx, EXLA and Evision
Mix.install(
[
{:nx, "~> 0.3"},
{:exla, "~> 0.3"},
{:evision, "~> 0.1.2", github: "cocoa-xu/evision", tag: "v0.1.2"}
],
config: [
nx: [default_backend: EXLA.Backend]
]
)
# you can replace src_file to any image file.
src_file = "ZACKY-3000.jpg"
# div_size is the width to divide the image.
div_size = 256
dst_file_ext = Path.extname(src_file)
dst_file_basename = Path.basename(src_file, dst_file_ext)
# dst_files is generated by Stream with counting up
dst_files =
Stream.unfold(0, fn counter -> {counter, counter + 1} end)
|> Stream.map(& "#{dst_file_basename}_#{&1}#{dst_file_ext}")
div_img =
Evision.imread!(src_file)
|> Evision.Nx.to_nx()
|> Nx.to_batched_list(div_size) # here is the most important of this program.
|> Enum.map(& Evision.Nx.to_mat!(&1))
# generate dst_files to images
Enum.zip(div_img, dst_files)
|> Enum.map(fn {img, dst_file} -> Evision.imwrite!(dst_file, img) end)
@MIERAI
Copy link

MIERAI commented Dec 15, 2023

Evision.Nx.to_nx() ->Evision.Mat.to_nx()
Evision.Nx.to_mat!(&1) ->Evision.Mat.from_nx(&1)

@MIERAI
Copy link

MIERAI commented Dec 18, 2023

If an error occurs while writing the image, try using ImageWriter instead.

defmodule ImageWriter do
def write_image(img, dst_file) do
try do
Evision.imwrite(dst_file, img)
IO.puts("The image was successfully written to #{dst_file}")
rescue
_ ->
IO.puts("An error occurred while writing the image")
end
end
end

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