├── .formatter.exs ├── .github └── workflows │ └── test.yaml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib └── nx_image.ex ├── mix.exs ├── mix.lock ├── notebooks └── examples.livemd └── test ├── nx_image_test.exs ├── support └── test_helpers.ex └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | main: 10 | runs-on: ubuntu-latest 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | include: 15 | - pair: 16 | elixir: 1.13.0 17 | otp: 24.0 18 | lint: true 19 | env: 20 | MIX_ENV: test 21 | steps: 22 | - uses: actions/checkout@v3 23 | - uses: erlef/setup-beam@v1 24 | with: 25 | otp-version: ${{ matrix.pair.otp }} 26 | elixir-version: ${{ matrix.pair.elixir }} 27 | - uses: actions/cache@v3 28 | with: 29 | path: | 30 | deps 31 | _build 32 | key: ${{ runner.os }}-mix-${{ matrix.pair.elixir }}-${{ matrix.pair.otp }}-${{ hashFiles('**/mix.lock') }} 33 | restore-keys: | 34 | ${{ runner.os }}-mix- 35 | - run: mix deps.get 36 | - run: mix format --check-formatted 37 | if: ${{ matrix.lint }} 38 | - run: mix deps.unlock --check-unused 39 | if: ${{ matrix.lint }} 40 | - run: mix deps.compile 41 | - run: mix compile --warnings-as-errors 42 | if: ${{ matrix.lint }} 43 | - run: mix test 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | nx_image-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [v0.1.2](https://github.com/elixir-nx/nx_image/tree/v0.1.2) (2024-02-19) 9 | 10 | ### Added 11 | 12 | * `:antialias` option to control anti-aliasing in resize functions ([#5](https://github.com/elixir-nx/nx_image/pull/5)) 13 | 14 | ## [v0.1.1](https://github.com/elixir-nx/nx_image/tree/v0.1.1) (2023-03-16) 15 | 16 | ### Fixed 17 | 18 | * Deprecation warnings on Nx 0.5 ([#4](https://github.com/elixir-nx/nx_image/pull/4)) 19 | 20 | ## [v0.1.0](https://github.com/elixir-nx/nx_image/tree/v0.1.0) (2022-12-05) 21 | 22 | Initial release. 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NxImage 2 | 3 | [![Actions Status](https://github.com/elixir-nx/nx_image/workflows/Test/badge.svg)](https://github.com/elixir-nx/nx_image/actions) 4 | [![Docs](https://img.shields.io/badge/docs-gray.svg)](https://hexdocs.pm/nx_image) 5 | 6 | Image processing in [Nx](https://github.com/elixir-nx/nx). 7 | 8 | ## Installation 9 | 10 | You can add the `:nx_image` dependency to your `mix.exs`: 11 | 12 | ```elixir 13 | def deps do 14 | [ 15 | {:nx_image, "~> 0.1.2"} 16 | ] 17 | end 18 | ``` 19 | 20 | ## License 21 | 22 | Copyright (C) 2022 Dashbit 23 | 24 | Licensed under the Apache License, Version 2.0 (the "License"); 25 | you may not use this file except in compliance with the License. 26 | You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 27 | 28 | Unless required by applicable law or agreed to in writing, software 29 | distributed under the License is distributed on an "AS IS" BASIS, 30 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 31 | See the License for the specific language governing permissions and 32 | limitations under the License. 33 | -------------------------------------------------------------------------------- /lib/nx_image.ex: -------------------------------------------------------------------------------- 1 | defmodule NxImage do 2 | @moduledoc """ 3 | Image processing in `Nx`. 4 | 5 | All functions expect images to be tensors in either HWC or CHW order, 6 | with an arbitrary number of leading batch axes. 7 | 8 | All transformations preserve the input type, rounding if necessary. 9 | For higher precision, cast the input to floating-point beforehand. 10 | """ 11 | 12 | import Nx.Defn 13 | 14 | @doc """ 15 | Crops an image at the center. 16 | 17 | If the image is too small to be cropped to the desired size, it gets 18 | padded with zeros. 19 | 20 | ## Options 21 | 22 | * `:channels` - channels location, either `:first` or `:last`. 23 | Defaults to `:last` 24 | 25 | ## Examples 26 | 27 | iex> image = Nx.iota({4, 4, 1}, type: :u8) 28 | iex> NxImage.center_crop(image, {2, 2}) 29 | #Nx.Tensor< 30 | u8[2][2][1] 31 | [ 32 | [ 33 | [5], 34 | [6] 35 | ], 36 | [ 37 | [9], 38 | [10] 39 | ] 40 | ] 41 | > 42 | 43 | iex> image = Nx.iota({2, 2, 1}, type: :u8) 44 | iex> NxImage.center_crop(image, {1, 4}) 45 | #Nx.Tensor< 46 | u8[1][4][1] 47 | [ 48 | [ 49 | [0], 50 | [0], 51 | [1], 52 | [0] 53 | ] 54 | ] 55 | > 56 | 57 | """ 58 | @doc type: :transformation 59 | deftransform center_crop(input, size, opts \\ []) when is_tuple(size) do 60 | opts = Keyword.validate!(opts, channels: :last) 61 | validate_image!(input) 62 | 63 | pad_config = 64 | for {axis, size, out_size} <- spatial_axes_with_sizes(input, size, opts[:channels]), 65 | reduce: List.duplicate({0, 0, 0}, Nx.rank(input)) do 66 | pad_config -> 67 | low = div(size - out_size, 2) 68 | high = low + out_size 69 | List.replace_at(pad_config, axis, {-low, high - size, 0}) 70 | end 71 | 72 | Nx.pad(input, 0, pad_config) 73 | end 74 | 75 | deftransformp spatial_axes_with_sizes(input, size, channels) do 76 | {height_axis, width_axis} = spatial_axes(input, channels) 77 | {height, width} = size(input, channels) 78 | {out_height, out_width} = size 79 | [{height_axis, height, out_height}, {width_axis, width, out_width}] 80 | end 81 | 82 | # Returns the image size as `{height, width}`. 83 | deftransformp size(input, channels) do 84 | {height_axis, width_axis} = spatial_axes(input, channels) 85 | {Nx.axis_size(input, height_axis), Nx.axis_size(input, width_axis)} 86 | end 87 | 88 | @doc """ 89 | Resizes an image. 90 | 91 | ## Options 92 | 93 | * `:method` - the resizing method to use, either of `:nearest`, 94 | `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`. Defaults to 95 | `:bilinear` 96 | 97 | * `:antialias` - whether an anti-aliasing filter should be used 98 | when downsampling. This has no effect with upsampling. Defaults 99 | to `true` 100 | 101 | * `:channels` - channels location, either `:first` or `:last`. 102 | Defaults to `:last` 103 | 104 | ## Examples 105 | 106 | iex> image = Nx.iota({2, 2, 1}, type: :u8) 107 | iex> NxImage.resize(image, {3, 3}, method: :nearest) 108 | #Nx.Tensor< 109 | u8[3][3][1] 110 | [ 111 | [ 112 | [0], 113 | [1], 114 | [1] 115 | ], 116 | [ 117 | [2], 118 | [3], 119 | [3] 120 | ], 121 | [ 122 | [2], 123 | [3], 124 | [3] 125 | ] 126 | ] 127 | > 128 | 129 | iex> image = Nx.iota({2, 2, 1}, type: :f32) 130 | iex> NxImage.resize(image, {3, 3}, method: :bilinear) 131 | #Nx.Tensor< 132 | f32[3][3][1] 133 | [ 134 | [ 135 | [0.0], 136 | [0.5], 137 | [1.0] 138 | ], 139 | [ 140 | [1.0], 141 | [1.5], 142 | [2.0] 143 | ], 144 | [ 145 | [2.0], 146 | [2.5], 147 | [3.0] 148 | ] 149 | ] 150 | > 151 | 152 | """ 153 | @doc type: :transformation 154 | deftransform resize(input, size, opts \\ []) when is_tuple(size) do 155 | opts = Keyword.validate!(opts, channels: :last, method: :bilinear, antialias: true) 156 | validate_image!(input) 157 | 158 | {spatial_axes, out_shape} = 159 | input 160 | |> spatial_axes_with_sizes(size, opts[:channels]) 161 | |> Enum.reject(fn {_axis, size, out_size} -> Elixir.Kernel.==(size, out_size) end) 162 | |> Enum.map_reduce(Nx.shape(input), fn {axis, _size, out_size}, out_shape -> 163 | {axis, put_elem(out_shape, axis, out_size)} 164 | end) 165 | 166 | antialias = opts[:antialias] 167 | 168 | resized_input = 169 | case opts[:method] do 170 | :nearest -> 171 | resize_nearest(input, out_shape, spatial_axes) 172 | 173 | :bilinear -> 174 | resize_with_kernel(input, out_shape, spatial_axes, antialias, &fill_linear_kernel/1) 175 | 176 | :bicubic -> 177 | resize_with_kernel(input, out_shape, spatial_axes, antialias, &fill_cubic_kernel/1) 178 | 179 | :lanczos3 -> 180 | resize_with_kernel( 181 | input, 182 | out_shape, 183 | spatial_axes, 184 | antialias, 185 | &fill_lanczos_kernel(3, &1) 186 | ) 187 | 188 | :lanczos5 -> 189 | resize_with_kernel( 190 | input, 191 | out_shape, 192 | spatial_axes, 193 | antialias, 194 | &fill_lanczos_kernel(5, &1) 195 | ) 196 | 197 | method -> 198 | raise ArgumentError, 199 | "expected :method to be either of :nearest, :bilinear, :bicubic, " <> 200 | ":lanczos3, :lanczos5, got: #{inspect(method)}" 201 | end 202 | 203 | cast_to(resized_input, input) 204 | end 205 | 206 | deftransformp spatial_axes(input, channels) do 207 | axes = 208 | case channels do 209 | :first -> [-2, -1] 210 | :last -> [-3, -2] 211 | end 212 | 213 | axes 214 | |> Enum.map(&Nx.axis_index(input, &1)) 215 | |> List.to_tuple() 216 | end 217 | 218 | defnp cast_to(left, right) do 219 | left_type = Nx.type(left) 220 | right_type = Nx.type(right) 221 | 222 | left = 223 | if Nx.Type.float?(left_type) and Nx.Type.integer?(right_type) do 224 | Nx.round(left) 225 | else 226 | left 227 | end 228 | 229 | left 230 | |> Nx.as_type(right_type) 231 | |> Nx.reshape(left, names: Nx.names(right)) 232 | end 233 | 234 | deftransformp resize_nearest(input, out_shape, spatial_axes) do 235 | singular_shape = List.duplicate(1, Nx.rank(input)) |> List.to_tuple() 236 | 237 | for axis <- spatial_axes, reduce: input do 238 | input -> 239 | input_shape = Nx.shape(input) 240 | input_size = elem(input_shape, axis) 241 | output_size = elem(out_shape, axis) 242 | inv_scale = input_size / output_size 243 | offset = Nx.iota({output_size}) |> Nx.add(0.5) |> Nx.multiply(inv_scale) 244 | offset = offset |> Nx.floor() |> Nx.as_type({:s, 32}) 245 | 246 | offset = 247 | offset 248 | |> Nx.reshape(put_elem(singular_shape, axis, output_size)) 249 | |> Nx.broadcast(put_elem(input_shape, axis, output_size)) 250 | 251 | Nx.take_along_axis(input, offset, axis: axis) 252 | end 253 | end 254 | 255 | @f32_eps :math.pow(2, -23) 256 | 257 | deftransformp resize_with_kernel(input, out_shape, spatial_axes, antialias, kernel_fun) do 258 | for axis <- spatial_axes, reduce: input do 259 | input -> 260 | resize_axis_with_kernel(input, 261 | axis: axis, 262 | output_size: elem(out_shape, axis), 263 | antialias: antialias, 264 | kernel_fun: kernel_fun 265 | ) 266 | end 267 | end 268 | 269 | defnp resize_axis_with_kernel(input, opts) do 270 | axis = opts[:axis] 271 | output_size = opts[:output_size] 272 | antialias = opts[:antialias] 273 | kernel_fun = opts[:kernel_fun] 274 | 275 | input_size = Nx.axis_size(input, axis) 276 | 277 | inv_scale = input_size / output_size 278 | 279 | kernel_scale = 280 | if antialias do 281 | max(1, inv_scale) 282 | else 283 | 1 284 | end 285 | 286 | sample_f = (Nx.iota({1, output_size}) + 0.5) * inv_scale - 0.5 287 | x = Nx.abs(sample_f - Nx.iota({input_size, 1})) / kernel_scale 288 | weights = kernel_fun.(x) 289 | 290 | weights_sum = Nx.sum(weights, axes: [0], keep_axes: true) 291 | 292 | weights = Nx.select(Nx.abs(weights) > 1000 * @f32_eps, safe_divide(weights, weights_sum), 0) 293 | 294 | input = Nx.dot(input, [axis], weights, [0]) 295 | # The transformed axis is moved to the end, so we transpose back 296 | reorder_axis(input, -1, axis) 297 | end 298 | 299 | defnp fill_linear_kernel(x) do 300 | Nx.max(0, 1 - x) 301 | end 302 | 303 | defnp fill_cubic_kernel(x) do 304 | # See https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm 305 | out = (1.5 * x - 2.5) * x * x + 1 306 | out = Nx.select(x >= 1, ((-0.5 * x + 2.5) * x - 4) * x + 2, out) 307 | Nx.select(x >= 2, 0, out) 308 | end 309 | 310 | @pi :math.pi() 311 | 312 | defnp fill_lanczos_kernel(radius, x) do 313 | y = radius * Nx.sin(@pi * x) * Nx.sin(@pi * x / radius) 314 | out = Nx.select(x > 1.0e-3, safe_divide(y, @pi ** 2 * x ** 2), 1) 315 | Nx.select(x > radius, 0, out) 316 | end 317 | 318 | defnp safe_divide(x, y) do 319 | x / Nx.select(y != 0, y, 1) 320 | end 321 | 322 | deftransformp reorder_axis(tensor, axis, target_axis) do 323 | axes = Nx.axes(tensor) 324 | {source_axis, axes} = List.pop_at(axes, axis) 325 | axes = List.insert_at(axes, target_axis, source_axis) 326 | Nx.transpose(tensor, axes: axes) 327 | end 328 | 329 | @doc """ 330 | Scales an image such that the short edge matches the given size. 331 | 332 | ## Options 333 | 334 | * `:method` - the resizing method to use, same as `resize/2` 335 | 336 | * `:antialias` - whether an anti-aliasing filter should be used 337 | when downsampling. This has no effect with upsampling. Defaults 338 | to `true` 339 | 340 | * `:channels` - channels location, either `:first` or `:last`. 341 | Defaults to `:last` 342 | 343 | ## Examples 344 | 345 | iex> image = Nx.iota({2, 4, 1}, type: :u8) 346 | iex> resized_image = NxImage.resize_short(image, 3, method: :nearest) 347 | iex> Nx.shape(resized_image) 348 | {3, 6, 1} 349 | 350 | iex> image = Nx.iota({4, 2, 1}, type: :u8) 351 | iex> resized_image = NxImage.resize_short(image, 3, method: :nearest) 352 | iex> Nx.shape(resized_image) 353 | {6, 3, 1} 354 | 355 | """ 356 | @doc type: :transformation 357 | deftransform resize_short(input, size, opts \\ []) when is_integer(size) do 358 | opts = Keyword.validate!(opts, channels: :last, method: :bilinear, antialias: true) 359 | validate_image!(input) 360 | resize_short_n(input, [size: size] ++ opts) 361 | end 362 | 363 | defnp resize_short_n(input, opts) do 364 | size = opts[:size] 365 | method = opts[:method] 366 | antialias = opts[:antialias] 367 | channels = opts[:channels] 368 | 369 | {height, width} = size(input, channels) 370 | {out_height, out_width} = resize_short_size(height, width, size) 371 | 372 | resize(input, {out_height, out_width}, 373 | method: method, 374 | antialias: antialias, 375 | channels: channels 376 | ) 377 | end 378 | 379 | deftransformp resize_short_size(height, width, size) do 380 | {short, long} = if height < width, do: {height, width}, else: {width, height} 381 | 382 | out_short = size 383 | out_long = floor(size * long / short) 384 | 385 | if height < width, do: {out_short, out_long}, else: {out_long, out_short} 386 | end 387 | 388 | @doc """ 389 | Normalizes an image according to the given per-channel mean and 390 | standard deviation. 391 | 392 | * `:channels` - channels location, either `:first` or `:last`. 393 | Defaults to `:last` 394 | 395 | ## Examples 396 | 397 | iex> image = Nx.iota({2, 2, 3}, type: :f32) 398 | iex> mean = Nx.tensor([0.485, 0.456, 0.406]) 399 | iex> std = Nx.tensor([0.229, 0.224, 0.225]) 400 | iex> NxImage.normalize(image, mean, std) 401 | #Nx.Tensor< 402 | f32[2][2][3] 403 | [ 404 | [ 405 | [-2.1179039478302, 2.4285714626312256, 7.084444522857666], 406 | [10.982532501220703, 15.821427345275879, 20.41777801513672] 407 | ], 408 | [ 409 | [24.08296775817871, 29.214284896850586, 33.7511100769043], 410 | [37.183406829833984, 42.607139587402344, 47.08444595336914] 411 | ] 412 | ] 413 | > 414 | 415 | """ 416 | @doc type: :transformation 417 | defn normalize(input, mean, std, opts \\ []) do 418 | opts = keyword!(opts, channels: :last) 419 | validate_image!(input) 420 | 421 | mean = broadcast_channel_info(mean, input, opts[:channels], "mean") 422 | std = broadcast_channel_info(std, input, opts[:channels], "std") 423 | 424 | normalized_input = (input - mean) / std 425 | 426 | cast_to(normalized_input, input) 427 | end 428 | 429 | deftransformp broadcast_channel_info(tensor, input, channels, name) do 430 | rank = Nx.rank(input) 431 | 432 | channels_axis = 433 | case channels do 434 | :first -> rank - 3 435 | :last -> rank - 1 436 | end 437 | 438 | num_channels = Nx.axis_size(input, channels_axis) 439 | 440 | case Nx.shape(tensor) do 441 | {^num_channels} -> 442 | :ok 443 | 444 | shape -> 445 | raise ArgumentError, 446 | "expected #{name} to have shape {#{num_channels}}, got: #{inspect(shape)}" 447 | end 448 | 449 | shape = 1 |> Tuple.duplicate(rank) |> put_elem(channels_axis, :auto) 450 | Nx.reshape(tensor, shape) 451 | end 452 | 453 | @doc """ 454 | Converts pixel values (0-255) into a continuous range. 455 | 456 | ## Examples 457 | 458 | iex> image = Nx.tensor([[[0], [128]], [[191], [255]]]) 459 | iex> NxImage.to_continuous(image, 0.0, 1.0) 460 | #Nx.Tensor< 461 | f32[2][2][1] 462 | [ 463 | [ 464 | [0.0], 465 | [0.501960813999176] 466 | ], 467 | [ 468 | [0.7490196228027344], 469 | [1.0] 470 | ] 471 | ] 472 | > 473 | 474 | iex> image = Nx.tensor([[[0], [128]], [[191], [255]]]) 475 | iex> NxImage.to_continuous(image, -1.0, 1.0) 476 | #Nx.Tensor< 477 | f32[2][2][1] 478 | [ 479 | [ 480 | [-1.0], 481 | [0.003921627998352051] 482 | ], 483 | [ 484 | [0.49803924560546875], 485 | [1.0] 486 | ] 487 | ] 488 | > 489 | 490 | """ 491 | @doc type: :conversion 492 | defn to_continuous(input, min, max) do 493 | validate_image!(input) 494 | 495 | input / 255.0 * (max - min) + min 496 | end 497 | 498 | @doc """ 499 | Converts values from continuous range into pixel values (0-255). 500 | 501 | ## Examples 502 | 503 | iex> image = Nx.tensor([[[0.0], [0.5]], [[0.75], [1.0]]]) 504 | iex> NxImage.from_continuous(image, 0.0, 1.0) 505 | #Nx.Tensor< 506 | u8[2][2][1] 507 | [ 508 | [ 509 | [0], 510 | [128] 511 | ], 512 | [ 513 | [191], 514 | [255] 515 | ] 516 | ] 517 | > 518 | 519 | iex> image = Nx.tensor([[[-1.0], [0.0]], [[0.5], [1.0]]]) 520 | iex> NxImage.from_continuous(image, -1.0, 1.0) 521 | #Nx.Tensor< 522 | u8[2][2][1] 523 | [ 524 | [ 525 | [0], 526 | [128] 527 | ], 528 | [ 529 | [191], 530 | [255] 531 | ] 532 | ] 533 | > 534 | 535 | """ 536 | @doc type: :conversion 537 | defn from_continuous(input, min, max) do 538 | validate_image!(input) 539 | 540 | input = (input - min) / (max - min) * 255.0 541 | 542 | input 543 | |> Nx.round() 544 | |> Nx.clip(0, 255) 545 | |> Nx.as_type(:u8) 546 | end 547 | 548 | deftransformp validate_image!(input) do 549 | rank = Nx.rank(input) 550 | 551 | if rank < 3 do 552 | raise ArgumentError, 553 | "expected the image input to have rank 3 or higher, got: #{inspect(rank)}" 554 | end 555 | end 556 | end 557 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule NxImage.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.1.2" 5 | @description "Image processing in Nx" 6 | 7 | def project do 8 | [ 9 | app: :nx_image, 10 | version: @version, 11 | description: @description, 12 | name: "NxImage", 13 | elixir: "~> 1.13", 14 | elixirc_paths: elixirc_paths(Mix.env()), 15 | start_permanent: Mix.env() == :prod, 16 | deps: deps(), 17 | docs: docs(), 18 | package: package() 19 | ] 20 | end 21 | 22 | def application do 23 | [] 24 | end 25 | 26 | defp elixirc_paths(:test), do: ["lib", "test/support"] 27 | defp elixirc_paths(_), do: ["lib"] 28 | 29 | defp deps do 30 | [ 31 | {:nx, "~> 0.4"}, 32 | {:ex_doc, "~> 0.29", only: :dev, runtime: false} 33 | ] 34 | end 35 | 36 | defp docs do 37 | [ 38 | main: "NxImage", 39 | source_url: "https://github.com/elixir-nx/nx_image", 40 | source_ref: "v#{@version}", 41 | extras: ["notebooks/examples.livemd"], 42 | groups_for_functions: [ 43 | Transformation: &(&1[:type] == :transformation), 44 | Conversion: &(&1[:type] == :conversion) 45 | ] 46 | ] 47 | end 48 | 49 | def package do 50 | [ 51 | licenses: ["Apache-2.0"], 52 | links: %{ 53 | "GitHub" => "https://github.com/elixir-nx/nx_image" 54 | } 55 | ] 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "complex": {:hex, :complex, "0.4.2", "923e5db0be13dbb3ea00cf8459d9f75f3afdd9ff5a82742ded21064330d28273", [:mix], [], "hexpm", "069a085ef820ce675a2619fd125b963ff4514af2102c7f7d7965128e5ec0a429"}, 3 | "earmark_parser": {:hex, :earmark_parser, "1.4.39", "424642f8335b05bb9eb611aa1564c148a8ee35c9c8a8bba6e129d51a3e3c6769", [:mix], [], "hexpm", "06553a88d1f1846da9ef066b87b57c6f605552cfbe40d20bd8d59cc6bde41944"}, 4 | "ex_doc": {:hex, :ex_doc, "0.31.1", "8a2355ac42b1cc7b2379da9e40243f2670143721dd50748bf6c3b1184dae2089", [:mix], [{:earmark_parser, "~> 1.4.39", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.1", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "3178c3a407c557d8343479e1ff117a96fd31bafe52a039079593fb0524ef61b0"}, 5 | "makeup": {:hex, :makeup, "1.1.1", "fa0bc768698053b2b3869fa8a62616501ff9d11a562f3ce39580d60860c3a55e", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "5dc62fbdd0de44de194898b6710692490be74baa02d9d108bc29f007783b0b48"}, 6 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.1", "cc9e3ca312f1cfeccc572b37a09980287e243648108384b97ff2b76e505c3555", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "e127a341ad1b209bd80f7bd1620a15693a9908ed780c3b763bccf7d200c767c6"}, 7 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.4", "29563475afa9b8a2add1b7a9c8fb68d06ca7737648f28398e04461f008b69521", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "f4ed47ecda66de70dd817698a703f8816daa91272e7e45812469498614ae8b29"}, 8 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 9 | "nx": {:hex, :nx, "0.4.0", "2ec2cebec6a9ac8a3d5ae8ef79345cf92f37f9018d50817684e51e97b86f3d36", [:mix], [{:complex, "~> 0.4.2", [hex: :complex, repo: "hexpm", optional: false]}], "hexpm", "bab955768dadfe2208723fbffc9255341b023291f2aabcbd25bf98167dd3399e"}, 10 | } 11 | -------------------------------------------------------------------------------- /notebooks/examples.livemd: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | ```elixir 4 | Mix.install([ 5 | {:nx, "~> 0.6.0"}, 6 | {:nx_image, "~> 0.1.2"}, 7 | {:kino, "~> 0.12.0"} 8 | ]) 9 | ``` 10 | 11 | ## Upload your test image 12 | 13 | Using a Livebook v0.8.0 or higher, we can add the new `Kino.Input.image/1` to upload an image to our notebook. 14 | 15 | ```elixir 16 | image_input = Kino.Input.image("Uploaded Image") 17 | ``` 18 | 19 | We can use `Input.read/1` to retrieve the information about our image. 20 | 21 | ```elixir 22 | %{file_ref: file_ref, format: :rgb, height: height, width: width} = Kino.Input.read(image_input) 23 | 24 | content = file_ref |> Kino.Input.file_path() |> File.read!() 25 | ``` 26 | 27 | NxImage requires that the images be tensors in either HWC (default) or CHW 28 | order, with an arbitrary number of leading batch axes. The input data is 29 | already HWC, so creating a tensor is straightforward: 30 | 31 | ```elixir 32 | image_tensor = 33 | Nx.from_binary(content, :u8) 34 | |> Nx.reshape({height, width, 3}) 35 | ``` 36 | 37 | Now that we have a tensor in the shape of `{height, width, channels}` we operate on it using the `NxImage` module. 38 | 39 | ## Center crop 40 | 41 | The first capability we'll look at is center cropping. 42 | 43 | ```elixir 44 | center_cropped_tensor = NxImage.center_crop(image_tensor, {300, 300}) 45 | ``` 46 | 47 | We've transformed the image from its original size to 300 x 300 by taking the pixels 150 above and below the image center. Similarly we have the 150 pixels to the left and right of the center point. 48 | 49 | ## Visualization 50 | 51 | Numbers are great, but most of us are visual focused. Let's see what center crop did to our uploaded image: 52 | 53 | ```elixir 54 | Kino.Layout.grid( 55 | [ 56 | Kino.Image.new(center_cropped_tensor), 57 | Kino.Markdown.new("**Center of the image**") 58 | ], 59 | boxed: true 60 | ) 61 | ``` 62 | 63 | ## Resize 64 | 65 | We'll resize the image. Whether this resized image is shrunk or enlarged is dependent upon the original image size. Resizing to a standard size can be useful when training visual models on a diverse set of source images. 66 | 67 | ```elixir 68 | resized_tensor = NxImage.resize(image_tensor, {768, 768}, method: :nearest) 69 | ``` 70 | 71 | Let's display the original image and the resized image. If you can't tell the difference, try a non-square image, or resizing to a very small resolution instead. 72 | 73 | ```elixir 74 | original_image = Kino.Image.new(image_tensor) 75 | original_label = Kino.Markdown.new("**Original image**") 76 | 77 | resized_image = Kino.Image.new(resized_tensor) 78 | resized_label = Kino.Markdown.new("**Resized image**") 79 | 80 | Kino.Layout.grid([ 81 | Kino.Layout.grid([original_image, original_label], boxed: true), 82 | Kino.Layout.grid([resized_image, resized_label], boxed: true) 83 | ]) 84 | ``` 85 | 86 | Let's double check the shape of both images. 87 | 88 | ```elixir 89 | {image_tensor.shape, resized_tensor.shape} 90 | ``` 91 | 92 | We can see that the resized image has a different shape from the original image shape. 93 | 94 | 95 | 96 | You can try other resize strategies: `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`. How do they affect the resulting image? 97 | 98 | ## Further exploration 99 | 100 | There are other functions in the `NxImage` module. 101 | 102 | For example, `NxImage.normalize/3` can be useful for transfer learning, where an original model is further trained on a set of images from your custom domain. The original images had a particular mean and standard deviation. When transfer learning from the base model, your source images are normalized in the same manner as the distribution of the original set of images. 103 | 104 | 105 | 106 | > Note: in this notebook we were using the default `Nx.BinaryBackend` for all the operations. To speed up the operations you can configure an optimised backend or compiler, such as `EXLA`. 107 | -------------------------------------------------------------------------------- /test/nx_image_test.exs: -------------------------------------------------------------------------------- 1 | defmodule NxImageTest do 2 | use ExUnit.Case 3 | 4 | import NxImage.TestHelpers 5 | 6 | doctest NxImage 7 | 8 | describe "resize/3" do 9 | test "methods" do 10 | # Reference values computed in jax 11 | 12 | image = Nx.iota({2, 2, 3}, type: :f32) 13 | 14 | assert NxImage.resize(image, {3, 3}, method: :nearest) == 15 | Nx.tensor([ 16 | [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [3.0, 4.0, 5.0]], 17 | [[6.0, 7.0, 8.0], [9.0, 10.0, 11.0], [9.0, 10.0, 11.0]], 18 | [[6.0, 7.0, 8.0], [9.0, 10.0, 11.0], [9.0, 10.0, 11.0]] 19 | ]) 20 | 21 | assert NxImage.resize(image, {3, 3}, method: :bilinear) == 22 | Nx.tensor([ 23 | [[0.0, 1.0, 2.0], [1.5, 2.5, 3.5], [3.0, 4.0, 5.0]], 24 | [[3.0, 4.0, 5.0], [4.5, 5.5, 6.5], [6.0, 7.0, 8.0]], 25 | [[6.0, 7.0, 8.0], [7.5, 8.5, 9.5], [9.0, 10.0, 11.0]] 26 | ]) 27 | 28 | assert_all_close( 29 | NxImage.resize(image, {3, 3}, method: :bicubic), 30 | Nx.tensor([ 31 | [[-0.5921, 0.4079, 1.4079], [1.1053, 2.1053, 3.1053], [2.8026, 3.8026, 4.8026]], 32 | [[2.8026, 3.8026, 4.8026], [4.5, 5.5, 6.5], [6.1974, 7.1974, 8.1974]], 33 | [[6.1974, 7.1974, 8.1974], [7.8947, 8.8947, 9.8947], [9.5921, 10.5921, 11.5921]] 34 | ]) 35 | ) 36 | 37 | assert_all_close( 38 | NxImage.resize(image, {3, 3}, method: :lanczos3), 39 | Nx.tensor([ 40 | [[-1.1173, -0.1173, 0.8827], [0.7551, 1.7551, 2.7551], [2.6276, 3.6276, 4.6276]], 41 | [[2.6276, 3.6276, 4.6276], [4.5, 5.5, 6.5], [6.3724, 7.3724, 8.3724]], 42 | [[6.3724, 7.3724, 8.3724], [8.2449, 9.2449, 10.2449], [10.1173, 11.1173, 12.1173]] 43 | ]) 44 | ) 45 | 46 | assert_all_close( 47 | NxImage.resize(image, {3, 3}, method: :lanczos5), 48 | Nx.tensor([ 49 | [[-1.3525, -0.3525, 0.6475], [0.5984, 1.5984, 2.5984], [2.5492, 3.5492, 4.5492]], 50 | [[2.5492, 3.5492, 4.5492], [4.5, 5.5, 6.5], [6.4508, 7.4508, 8.4508]], 51 | [[6.4508, 7.4508, 8.4508], [8.4016, 9.4016, 10.4016], [10.3525, 11.3525, 12.3525]] 52 | ]) 53 | ) 54 | end 55 | 56 | test "without anti-aliasing" do 57 | # Upscaling 58 | 59 | image = Nx.iota({4, 4, 3}, type: :f32) 60 | 61 | assert_all_close( 62 | NxImage.resize(image, {3, 3}, method: :bicubic, antialias: false), 63 | Nx.tensor([ 64 | [ 65 | [[1.5427, 2.5427, 3.5427], [5.7341, 6.7341, 7.7341], [9.9256, 10.9256, 11.9256]], 66 | [[18.3085, 19.3085, 20.3085], [22.5, 23.5, 24.5], [26.6915, 27.6915, 28.6915]], 67 | [ 68 | [35.0744, 36.0744, 37.0744], 69 | [39.2659, 40.2659, 41.2659], 70 | [43.4573, 44.4573, 45.4573] 71 | ] 72 | ] 73 | ]) 74 | ) 75 | 76 | # Downscaling (no effect) 77 | 78 | image = Nx.iota({2, 2, 3}, type: :f32) 79 | 80 | assert_all_close( 81 | NxImage.resize(image, {3, 3}, method: :bicubic, antialias: false), 82 | Nx.tensor([ 83 | [[-0.5921, 0.4079, 1.4079], [1.1053, 2.1053, 3.1053], [2.8026, 3.8026, 4.8026]], 84 | [[2.8026, 3.8026, 4.8026], [4.5, 5.5, 6.5], [6.1974, 7.1974, 8.1974]], 85 | [[6.1974, 7.1974, 8.1974], [7.8947, 8.8947, 9.8947], [9.5921, 10.5921, 11.5921]] 86 | ]) 87 | ) 88 | end 89 | 90 | test "accepts a batch" do 91 | image = Nx.iota({2, 2, 3}, type: :f32) 92 | resized_image = NxImage.resize(image, {3, 3}) 93 | 94 | batch_once = fn x -> Nx.stack([x, x]) end 95 | assert NxImage.resize(batch_once.(image), {3, 3}) == batch_once.(resized_image) 96 | 97 | batch_twice = fn x -> batch_once.(batch_once.(x)) end 98 | assert NxImage.resize(batch_twice.(image), {3, 3}) == batch_twice.(resized_image) 99 | end 100 | 101 | test "supports with channels-first" do 102 | image = Nx.iota({2, 2, 3}, type: :f32) 103 | resized_image = NxImage.resize(image, {3, 3}) 104 | 105 | to_channels_first = fn x -> Nx.transpose(x, axes: [2, 0, 1]) end 106 | 107 | assert NxImage.resize(to_channels_first.(image), {3, 3}, channels: :first) == 108 | to_channels_first.(resized_image) 109 | end 110 | end 111 | end 112 | -------------------------------------------------------------------------------- /test/support/test_helpers.ex: -------------------------------------------------------------------------------- 1 | defmodule NxImage.TestHelpers do 2 | @moduledoc false 3 | 4 | import ExUnit.Assertions 5 | 6 | def assert_all_close(left, right, opts \\ []) do 7 | atol = opts[:atol] || 1.0e-4 8 | rtol = opts[:rtol] || 1.0e-4 9 | 10 | equals = 11 | left 12 | |> Nx.all_close(right, atol: atol, rtol: rtol) 13 | |> Nx.backend_transfer(Nx.BinaryBackend) 14 | 15 | if equals != Nx.tensor(1, type: {:u, 8}, backend: Nx.BinaryBackend) do 16 | flunk(""" 17 | expected 18 | 19 | #{inspect(left)} 20 | 21 | to be within tolerance of 22 | 23 | #{inspect(right)} 24 | """) 25 | end 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------