@thi.ng/pixel-convolve 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Change Log
2
+
3
+ - **Last updated**: 2024-07-22T13:15:57Z
4
+ - **Generator**: [thi.ng/monopub](https://thi.ng/monopub)
5
+
6
+ All notable changes to this project will be documented in this file.
7
+ See [Conventional Commits](https://conventionalcommits.org/) for commit guidelines.
8
+
9
+ **Note:** Unlisted _patch_ versions only involve non-code or otherwise excluded changes
10
+ and/or version bumps of transitive dependencies.
11
+
12
+ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/pixel-convolve@0.1.0) (2024-07-22)
13
+
14
+ #### 🚀 Features
15
+
16
+ - import as new pkg ([#486](https://github.com/thi-ng/umbrella/issues/486)) ([5c3f4be](https://github.com/thi-ng/umbrella/commit/5c3f4be))
17
+ - migrate convolve, normalMap and imagePyramid functions
18
+ from [@thi.ng/pixel](https://github.com/thi-ng/umbrella/tree/main/packages/pixel) pkg
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,214 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+ <!-- Please see: https://github.com/thi-ng/umbrella/blob/develop/CONTRIBUTING.md#changes-to-readme-files -->
3
+ # ![@thi.ng/pixel-convolve](https://media.thi.ng/umbrella/banners-20230807/thing-pixel-convolve.svg?68dd5cd4)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/pixel-convolve.svg)](https://www.npmjs.com/package/@thi.ng/pixel-convolve)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/pixel-convolve.svg)
7
+ [![Mastodon Follow](https://img.shields.io/mastodon/follow/109331703950160316?domain=https%3A%2F%2Fmastodon.thi.ng&style=social)](https://mastodon.thi.ng/@toxi)
8
+
9
+ > [!NOTE]
10
+ > This is one of 198 standalone projects, maintained as part
11
+ > of the [@thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo
12
+ > and anti-framework.
13
+ >
14
+ > 🚀 Please help me to work full-time on these projects by [sponsoring me on
15
+ > GitHub](https://github.com/sponsors/postspectacular). Thank you! ❤️
16
+
17
+ - [About](#about)
18
+ - [Strided convolution & pooling](#strided-convolution--pooling)
19
+ - [Normal map generation](#normal-map-generation)
20
+ - [Status](#status)
21
+ - [Installation](#installation)
22
+ - [Dependencies](#dependencies)
23
+ - [Usage examples](#usage-examples)
24
+ - [API](#api)
25
+ - [Authors](#authors)
26
+ - [License](#license)
27
+
28
+ ## About
29
+
30
+ Extensible bitmap image convolution, kernel presets, normal map & image pyramid generation. This is a support package for [@thi.ng/pixel](https://github.com/thi-ng/umbrella/tree/develop/packages/pixel).
31
+
32
+ This package contains functionality which was previously part of and has been
33
+ extracted from the [@thi.ng/pixel](https://thi.ng/pixel) package.
34
+
35
+ - Convolution w/ arbitrary shaped/sized kernels, pooling, striding
36
+ - Convolution kernel & pooling kernels presets
37
+ - Higher order kernel generators (Gaussian, Lanczos)
38
+ - Image pooling filters (min/max, mean, adaptive threshold, custom)
39
+ - Image pyramid generation (w/ customizable kernels)
40
+ - Customizable normal map generation (i.e. X/Y gradients plus static Z component)
41
+
42
+ ### Strided convolution & pooling
43
+
44
+ Floating point buffers can be processed using arbitrary convolution kernels. The
45
+ following convolution kernel presets are provided for convenience:
46
+
47
+ | Kernel | Size |
48
+ |------------------|-------------|
49
+ | `BOX_BLUR3` | 3x3 |
50
+ | `BOX_BLUR5` | 5x5 |
51
+ | `GAUSSIAN_BLUR3` | 3x3 |
52
+ | `GAUSSIAN_BLUR5` | 5x5 |
53
+ | `GAUSSIAN(n)` | 2n+1 x 2n+1 |
54
+ | `HIGHPASS3` | 3x3 |
55
+ | `LANCZOS(a,s)` | as+1 x as+1 |
56
+ | `SHARPEN3` | 3x3 |
57
+ | `SOBEL_X` | 3x3 |
58
+ | `SOBEL_Y` | 3x3 |
59
+ | `UNSHARP_MASK5` | 5x5 |
60
+
61
+ Custom kernels can be defined (and code generated) using an array of
62
+ coefficients and a given kernel size. See above presets and
63
+ [`defKernel()`](https://docs.thi.ng/umbrella/pixel/functions/defKernel.html) for
64
+ reference.
65
+
66
+ Furthermore, convolution supports striding (i.e. only processing & keeping every
67
+ nth pixel column/row, aka downscaling) and pixel pooling (e.g. for ML
68
+ applications). Available pooling kernel presets (kernel sizes must be configured
69
+ independently):
70
+
71
+ | Kernel | Description |
72
+ |------------------------|--------------------|
73
+ | `POOL_MEAN` | Moving average |
74
+ | `POOL_MAX` | Local maximum |
75
+ | `POOL_MIN` | Local minimum |
76
+ | `POOL_NEAREST` | Nearest neighbor |
77
+ | `POOL_THRESHOLD(bias)` | Adaptive threshold |
78
+
79
+ Convolution can be applied to single, multiple or all channels of a
80
+ `FloatBuffer`. See
81
+ [`convolveChannel()`](https://docs.thi.ng/umbrella/pixel/functions/convolveChannel.html)
82
+ and
83
+ [`convolveImage()`](https://docs.thi.ng/umbrella/pixel/functions/convolveImage.html).
84
+
85
+ See
86
+ [ConvolveOpts](https://docs.thi.ng/umbrella/pixel/interfaces/ConvolveOpts.html)
87
+ for config options.
88
+
89
+ ```js tangle:export/readme-convolve.ts
90
+ import { floatBufferFromImage, FLOAT_RGB, imageFromURL } from "@thi.ng/pixel";
91
+ import { convolveImage, SOBEL_X } from "@thi.ng/pixel-convolve";
92
+
93
+ // convolutions are only available for float buffers (for now)
94
+ const src = floatBufferFromImage(await imageFromURL("test.jpg"), FLOAT_RGB);
95
+
96
+ // apply horizontal Sobel kernel preset to all channels
97
+ // downscale image by factor 2 (must be integer)
98
+ // scale kernel result values by factor 4
99
+ const dest = convolveImage(src, { kernel: SOBEL_X, stride: 2, scale: 4 });
100
+ ```
101
+
102
+ ### Normal map generation
103
+
104
+ Normal maps can be created via `normalMap()`. This function uses an adjustable
105
+ convolution kernel size to control gradient smoothness & details. Result X/Y
106
+ gradients can also be scaled (uniform or anisotropic) and the Z component can be
107
+ customized to (default: 1.0). The resulting image is in `FLOAT_NORMAL` format,
108
+ using signed channel values. This channel format is auto-translating these into
109
+ unsigned values when the image is converted into an integer format.
110
+
111
+ | Step | Scale = 1 | Scale = 2 | Scale = 4 | Scale = 8 |
112
+ |------|------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
113
+ | 0 | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-0-1.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-0-2.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-0-4.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-0-8.jpg) |
114
+ | 1 | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-1-1.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-1-2.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-1-4.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-1-8.jpg) |
115
+ | 2 | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-2-1.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-2-2.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-2-4.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-2-8.jpg) |
116
+ | 3 | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-3-1.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-3-2.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-3-4.jpg) | ![](https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/pixel/nmap-3-8.jpg) |
117
+
118
+ ```ts tangle:export/readme-normalmap.ts
119
+ import { ARGB8888, FLOAT_GRAY, floatBufferFromImage, imageFromURL } from "@thi.ng/pixel";
120
+ import { normalMap } from "@thi.ng/pixel-convolve";
121
+
122
+ // read source image into a single channel floating point buffer
123
+ const src = floatBufferFromImage(await imageFromURL("noise.png"), FLOAT_GRAY);
124
+
125
+ // create normal map (w/ default options)
126
+ // this results in a new float pixel buffer with FLOAT_RGB format
127
+ const nmap = normalMap(src, { step: 0, scale: 1 });
128
+
129
+ // pixel lookup (vectors are stored _un_normalized)
130
+ nmap.getAt(10, 10);
131
+ // Float32Array(3) [ -0.019607841968536377, -0.04313725233078003, 1 ]
132
+
133
+ // convert to 32bit packed int format
134
+ const nmapARGB = nmap.as(ARGB8888);
135
+ ```
136
+
137
+ ## Status
138
+
139
+ **STABLE** - used in production
140
+
141
+ [Search or submit any issues for this package](https://github.com/thi-ng/umbrella/issues?q=%5Bpixel-convolve%5D+in%3Atitle)
142
+
143
+ ## Installation
144
+
145
+ ```bash
146
+ yarn add @thi.ng/pixel-convolve
147
+ ```
148
+
149
+ ESM import:
150
+
151
+ ```ts
152
+ import * as pc from "@thi.ng/pixel-convolve";
153
+ ```
154
+
155
+ Browser ESM import:
156
+
157
+ ```html
158
+ <script type="module" src="https://esm.run/@thi.ng/pixel-convolve"></script>
159
+ ```
160
+
161
+ [JSDelivr documentation](https://www.jsdelivr.com/)
162
+
163
+ For Node.js REPL:
164
+
165
+ ```js
166
+ const pc = await import("@thi.ng/pixel-convolve");
167
+ ```
168
+
169
+ Package sizes (brotli'd, pre-treeshake): ESM: 2.27 KB
170
+
171
+ ## Dependencies
172
+
173
+ - [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
174
+ - [@thi.ng/checks](https://github.com/thi-ng/umbrella/tree/develop/packages/checks)
175
+ - [@thi.ng/errors](https://github.com/thi-ng/umbrella/tree/develop/packages/errors)
176
+ - [@thi.ng/math](https://github.com/thi-ng/umbrella/tree/develop/packages/math)
177
+ - [@thi.ng/pixel](https://github.com/thi-ng/umbrella/tree/develop/packages/pixel)
178
+
179
+ Note: @thi.ng/api is in _most_ cases a type-only import (not used at runtime)
180
+
181
+ ## Usage examples
182
+
183
+ Three projects in this repo's
184
+ [/examples](https://github.com/thi-ng/umbrella/tree/develop/examples)
185
+ directory are using this package:
186
+
187
+ | Screenshot | Description | Live demo | Source |
188
+ |:--------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------|:---------------------------------------------------------|:--------------------------------------------------------------------------------------|
189
+ | <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/adaptive-threshold.png" width="240"/> | Interactive image processing (adaptive threshold) | [Demo](https://demo.thi.ng/umbrella/adaptive-threshold/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/adaptive-threshold) |
190
+ | <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/geom-terrain-viz.jpg" width="240"/> | 2.5D hidden line visualization of digital elevation files (DEM) | [Demo](https://demo.thi.ng/umbrella/geom-terrain-viz/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/geom-terrain-viz) |
191
+ | <img src="https://raw.githubusercontent.com/thi-ng/umbrella/develop/assets/examples/pixel-normal-map.jpg" width="240"/> | Normal map creation/conversion basics | [Demo](https://demo.thi.ng/umbrella/pixel-normal-map/) | [Source](https://github.com/thi-ng/umbrella/tree/develop/examples/pixel-normal-map) |
192
+
193
+ ## API
194
+
195
+ [Generated API docs](https://docs.thi.ng/umbrella/pixel-convolve/)
196
+
197
+ ## Authors
198
+
199
+ - [Karsten Schmidt](https://thi.ng)
200
+
201
+ If this project contributes to an academic publication, please cite it as:
202
+
203
+ ```bibtex
204
+ @misc{thing-pixel-convolve,
205
+ title = "@thi.ng/pixel-convolve",
206
+ author = "Karsten Schmidt",
207
+ note = "https://thi.ng/pixel-convolve",
208
+ year = 2021
209
+ }
210
+ ```
211
+
212
+ ## License
213
+
214
+ &copy; 2021 - 2024 Karsten Schmidt // Apache License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,91 @@
1
+ import type { FloatArray, Fn, Fn3, FnN3, NumericArray } from "@thi.ng/api";
2
+ import type { IPixelBuffer } from "@thi.ng/pixel";
3
+ export type PoolTemplate = Fn3<string[], number, number, string>;
4
+ export interface ConvolutionKernelSpec {
5
+ /**
6
+ * Kernel coefficients.
7
+ */
8
+ spec: NumericArray;
9
+ /**
10
+ * Kernel size. If given as number, expands to `[size, size]`.
11
+ */
12
+ size: number | [number, number];
13
+ }
14
+ export interface PoolKernelSpec {
15
+ /**
16
+ * Code template function for {@link defKernel}.
17
+ */
18
+ pool: PoolTemplate;
19
+ /**
20
+ * Kernel size. If given as number, expands to `[size, size]`.
21
+ */
22
+ size: number | [number, number];
23
+ }
24
+ export interface KernelFnSpec {
25
+ /**
26
+ * Kernel factory.
27
+ */
28
+ fn: Fn<IPixelBuffer<FloatArray, NumericArray>, FnN3>;
29
+ /**
30
+ * Kernel size. If given as number, expands to `[size, size]`.
31
+ */
32
+ size: number | [number, number];
33
+ }
34
+ export type KernelSpec = ConvolutionKernelSpec | PoolKernelSpec | KernelFnSpec;
35
+ export interface ConvolveOpts {
36
+ /**
37
+ * Convolution kernel details/implementation.
38
+ */
39
+ kernel: KernelSpec;
40
+ /**
41
+ * Channel ID to convolve.
42
+ *
43
+ * @defaultValue 0
44
+ */
45
+ channel?: number;
46
+ /**
47
+ * Result scale factor
48
+ *
49
+ * @defaultValue 1
50
+ */
51
+ scale?: number;
52
+ /**
53
+ * Step size to process only every nth pixel.
54
+ *
55
+ * @defaultValue 1
56
+ */
57
+ stride?: number | [number, number];
58
+ /**
59
+ * Pixel read offset, only to be used for pooling operations. Should be set
60
+ * to `kernelSize/2`, and for the X-axis MUST be in `[0,stride)` interval.
61
+ */
62
+ offset?: number | [number, number];
63
+ }
64
+ export interface NormalMapOpts {
65
+ /**
66
+ * Channel ID to use for gradient extraction in source image.
67
+ *
68
+ * @defaultValue 0
69
+ */
70
+ channel: number;
71
+ /**
72
+ * Step size (aka number of pixels) between left/right, top/bottom
73
+ * neighbors.
74
+ *
75
+ * @defaultValue 0
76
+ */
77
+ step: number;
78
+ /**
79
+ * Result gradient scale factor(s).
80
+ *
81
+ * @defaultValue 1
82
+ */
83
+ scale: number | [number, number];
84
+ /**
85
+ * Z-axis value to use in blue channel of normal map.
86
+ *
87
+ * @defaultValue 1
88
+ */
89
+ z: number;
90
+ }
91
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
File without changes
package/convolve.d.ts ADDED
@@ -0,0 +1,155 @@
1
+ import type { Fn, FnN3, NumericArray } from "@thi.ng/api";
2
+ import { FloatBuffer } from "@thi.ng/pixel/float";
3
+ import type { ConvolutionKernelSpec, ConvolveOpts, KernelFnSpec, KernelSpec, PoolTemplate } from "./api.js";
4
+ /**
5
+ * Convolves a single channel from given `src` float buffer with provided
6
+ * convolution or pooling kernel with support for strided sampling (resulting in
7
+ * smaller dimensions). Returns result as single channel buffer (in
8
+ * {@link FLOAT_GRAY} format).
9
+ *
10
+ * @remarks
11
+ * Use {@link convolveImage} to process multiple or all channels in a buffer.
12
+ *
13
+ * References:
14
+ * - https://en.wikipedia.org/wiki/Kernel_(image_processing)
15
+ *
16
+ * @param src -
17
+ * @param opts -
18
+ */
19
+ export declare const convolveChannel: (src: FloatBuffer, opts: ConvolveOpts) => FloatBuffer;
20
+ /**
21
+ * Similar to {@link convolveChannel}, but processes multiple or all channels
22
+ * (default) in a buffer and returns a new buffer in same format as original.
23
+ *
24
+ * @remarks
25
+ * This function re-uses as much as internal state & memory as possible, so will
26
+ * be faster than individual applications of {@link convolveChannel}.
27
+ *
28
+ * @param src -
29
+ * @param opts -
30
+ */
31
+ export declare const convolveImage: (src: FloatBuffer, opts: Exclude<ConvolveOpts, "channel"> & {
32
+ channels?: number[];
33
+ }) => FloatBuffer;
34
+ /**
35
+ * HOF convolution or pooling kernel code generator. Takes either a
36
+ * {@link PoolTemplate} function or array of kernel coefficients and kernel
37
+ * width/height. Returns optimized kernel function for use with
38
+ * {@link __convolve}. If `normalize` is true (default: false), the given
39
+ * coefficients are divided by their sum (only used if provided as array).
40
+ *
41
+ * @remarks
42
+ * If total kernel size (width * height) is < 512, the result function will use
43
+ * unrolled loops to access pixels and hence kernel sizes shouldn't be larger
44
+ * than ~22x22 to avoid excessive function bodies. For dynamically generated
45
+ * kernel functions, only non-zero weighted pixels will be included in the
46
+ * result function to avoid extraneous lookups. Row & column offsets are
47
+ * pre-calculated too. Larger kernel sizes are handled via
48
+ * {@link defLargeKernel}.
49
+ *
50
+ * @param tpl -
51
+ * @param w -
52
+ * @param h -
53
+ * @param normalize -
54
+ */
55
+ export declare const defKernel: (tpl: NumericArray | PoolTemplate, w: number, h: number, normalize?: boolean) => Fn<FloatBuffer, FnN3>;
56
+ /**
57
+ * Loop based fallback for {@link defKernel}, intended for larger kernel sizes
58
+ * for which loop-unrolled approach is prohibitive. If `normalize` is true
59
+ * (default: false), the given coefficients are divided by their sum.
60
+ *
61
+ * @param kernel -
62
+ * @param w -
63
+ * @param h -
64
+ * @param normalize -
65
+ */
66
+ export declare const defLargeKernel: (kernel: NumericArray, w: number, h: number, normalize?: boolean) => Fn<FloatBuffer, FnN3>;
67
+ export declare const POOL_NEAREST: PoolTemplate;
68
+ export declare const POOL_MEAN: PoolTemplate;
69
+ export declare const POOL_MIN: PoolTemplate;
70
+ export declare const POOL_MAX: PoolTemplate;
71
+ /**
72
+ * Higher order adaptive threshold {@link PoolTemplate}. Computes: `step(C -
73
+ * mean(K) + B)`, where `C` is the center pixel, `K` the entire set of pixels in
74
+ * the kernel and `B` an arbitrary bias/offset value.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { convolveChannel, POOL_THRESHOLD } from "@thi.ng/pixel";
79
+ *
80
+ * // 3x3 adaptive threshold w/ bias = 1
81
+ * convolveChannel(src, { kernel: { pool: POOL_THRESHOLD(1), size: 3 }});
82
+ * ```
83
+ *
84
+ * @param bias -
85
+ */
86
+ export declare const POOL_THRESHOLD: (bias?: number) => PoolTemplate;
87
+ export declare const SOBEL_X: KernelSpec;
88
+ export declare const SOBEL_Y: KernelSpec;
89
+ export declare const SHARPEN3: KernelSpec;
90
+ export declare const HIGHPASS3: KernelSpec;
91
+ export declare const BOX_BLUR3: KernelSpec;
92
+ export declare const BOX_BLUR5: KernelSpec;
93
+ export declare const GAUSSIAN_BLUR3: KernelSpec;
94
+ export declare const GAUSSIAN_BLUR5: KernelSpec;
95
+ /**
96
+ * Higher order Gaussian blur kernel for given pixel radius `r` (integer).
97
+ * Returns {@link ConvolutionKernelSpec} with resulting kernel size of `2r+1`.
98
+ *
99
+ * @param r -
100
+ */
101
+ export declare const GAUSSIAN: (r: number) => ConvolutionKernelSpec;
102
+ /**
103
+ * Higher-order Lanczos filter kernel generator for given `a` value (recommended
104
+ * 2 or 3) and `scale` (num pixels per `a`).
105
+ *
106
+ * @remarks
107
+ * https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel
108
+ *
109
+ * @param a -
110
+ * @param scale -
111
+ */
112
+ export declare const LANCZOS: (a: number, scale?: number) => ConvolutionKernelSpec;
113
+ export declare const UNSHARP_MASK5: KernelSpec;
114
+ /**
115
+ * 3x3 convolution kernel to detect local maxima in a Von Neumann neighborhood.
116
+ * Returns in 1.0 if the center pixel is either higher valued than A & D or B & C,
117
+ * otherwise return zero.
118
+ *
119
+ * @remarks
120
+ * ```text
121
+ * |---|---|---|
122
+ * | | A | |
123
+ * |---|---|---|
124
+ * | B | X | C |
125
+ * |---|---|---|
126
+ * | | D | |
127
+ * |---|---|---|
128
+ * ```
129
+ *
130
+ * Also see {@link MAXIMA4_DIAG} for alternative.
131
+ */
132
+ export declare const MAXIMA4_CROSS: KernelFnSpec;
133
+ /**
134
+ * Similar to {@link MAXIMA4_CROSS}, a 3x3 convolution kernel to detect local
135
+ * maxima in a 45 degree rotated Von Neumann neighborhood. Returns in 1.0 if the
136
+ * center pixel is either higher valued than A & D or B & C, otherwise return
137
+ * zero.
138
+ *
139
+ * @remarks
140
+ * ```text
141
+ * |---|---|---|
142
+ * | A | | B |
143
+ * |---|---|---|
144
+ * | | X | |
145
+ * |---|---|---|
146
+ * | C | | D |
147
+ * |---|---|---|
148
+ * ```
149
+ */
150
+ export declare const MAXIMA4_DIAG: KernelFnSpec;
151
+ /**
152
+ * Union kernel of {@link MAXIMA4_CROSS} and {@link MAXIMA4_DIAG}.
153
+ */
154
+ export declare const MAXIMA8: KernelFnSpec;
155
+ //# sourceMappingURL=convolve.d.ts.map
package/convolve.js ADDED
@@ -0,0 +1,382 @@
1
+ import { isFunction } from "@thi.ng/checks/is-function";
2
+ import { assert } from "@thi.ng/errors/assert";
3
+ import { clamp } from "@thi.ng/math/interval";
4
+ import { lanczos } from "@thi.ng/math/mix";
5
+ import { ensureChannel } from "@thi.ng/pixel/checks";
6
+ import { FloatBuffer } from "@thi.ng/pixel/float";
7
+ import { FLOAT_GRAY } from "@thi.ng/pixel/format/float-gray";
8
+ import { __range } from "@thi.ng/pixel/internal/range";
9
+ import { __asIntVec } from "@thi.ng/pixel/internal/utils";
10
+ const convolveChannel = (src, opts) => __convolve(__initConvolve(src, opts));
11
+ const convolveImage = (src, opts) => {
12
+ const state = __initConvolve(src, opts);
13
+ const dest = new FloatBuffer(state.dwidth, state.dheight, src.format);
14
+ for (let channel of opts.channels || __range(src.format.channels.length)) {
15
+ dest.setChannel(channel, __convolve({ ...state, channel }));
16
+ }
17
+ return dest;
18
+ };
19
+ const __convolve = ({
20
+ channel,
21
+ dest,
22
+ dwidth,
23
+ dheight,
24
+ kernel,
25
+ offsetX,
26
+ offsetY,
27
+ rowStride,
28
+ scale,
29
+ src,
30
+ srcStride,
31
+ strideX,
32
+ strideY
33
+ }) => {
34
+ ensureChannel(src.format, channel);
35
+ const dpix = dest.data;
36
+ const stepX = strideX * srcStride;
37
+ const stepY = strideY * rowStride;
38
+ for (let sy = offsetY * rowStride, dy = 0, i = 0; dy < dheight; sy += stepY, dy++) {
39
+ for (let sx = offsetX * srcStride + channel, dx = 0; dx < dwidth; sx += stepX, dx++, i++) {
40
+ dpix[i] = kernel(sx, sy, channel) * scale;
41
+ }
42
+ }
43
+ return dest;
44
+ };
45
+ const __initKernel = (src, kernel, kw, kh) => (isFunction(kernel.fn) ? kernel.fn : defKernel(
46
+ kernel.spec || kernel.pool,
47
+ kw,
48
+ kh
49
+ ))(src);
50
+ const __initConvolve = (src, opts) => {
51
+ const {
52
+ channel = 0,
53
+ offset = 0,
54
+ scale = 1,
55
+ stride: sampleStride = 1,
56
+ kernel
57
+ } = opts;
58
+ const size = kernel.size;
59
+ const [kw, kh] = __asIntVec(size);
60
+ const [strideX, strideY] = __asIntVec(sampleStride);
61
+ const [offsetX, offsetY] = __asIntVec(offset);
62
+ assert(strideX >= 1 && strideY >= 1, `illegal stride: ${sampleStride}`);
63
+ const {
64
+ size: [width, height],
65
+ stride: [srcStride, rowStride]
66
+ } = src;
67
+ const dwidth = Math.floor(width / strideX);
68
+ const dheight = Math.floor(height / strideY);
69
+ assert(dwidth > 0 && dheight > 0, `too large stride(s) for given image`);
70
+ const dest = new FloatBuffer(dwidth, dheight, FLOAT_GRAY);
71
+ return {
72
+ channel,
73
+ dest,
74
+ dheight,
75
+ dwidth,
76
+ kernel: __initKernel(src, kernel, kw, kh),
77
+ offsetX,
78
+ offsetY,
79
+ rowStride,
80
+ scale,
81
+ src,
82
+ srcStride,
83
+ strideX,
84
+ strideY
85
+ };
86
+ };
87
+ const __declOffset = (idx, i, pre, stride, min2, max2) => idx < 0 ? `const ${pre}${i} = max(${pre}${idx < -1 ? idx + "*" : "-"}${stride},${min2});` : `const ${pre}${i} = min(${pre}+${idx > 1 ? idx + "*" : ""}${stride},${max2});`;
88
+ const defKernel = (tpl, w, h, normalize = false) => {
89
+ if (w * h > 512 && !isFunction(tpl))
90
+ return defLargeKernel(tpl, w, h, normalize);
91
+ const isPool = isFunction(tpl);
92
+ const prefix = [];
93
+ const body = [];
94
+ const kvars = [];
95
+ const h2 = h >> 1;
96
+ const w2 = w >> 1;
97
+ if (normalize) tpl = __normalize(tpl);
98
+ for (let y = 0, i = 0; y < h; y++) {
99
+ const yy = y - h2;
100
+ const row = [];
101
+ for (let x = 0; x < w; x++, i++) {
102
+ const kv = `k${y}_${x}`;
103
+ kvars.push(kv);
104
+ const xx = x - w2;
105
+ const idx = (yy !== 0 ? `y${y}` : `y`) + (xx !== 0 ? `+x${x}` : "+x");
106
+ isPool ? row.push(`pix[${idx}]`) : tpl[i] !== 0 && row.push(`${kv}*pix[${idx}]`);
107
+ if (y === 0 && xx !== 0) {
108
+ prefix.push(
109
+ __declOffset(
110
+ xx,
111
+ x,
112
+ "x",
113
+ "stride",
114
+ "channel",
115
+ "maxX+channel"
116
+ )
117
+ );
118
+ }
119
+ }
120
+ row.length && body.push(...row);
121
+ if (yy !== 0) {
122
+ prefix.push(__declOffset(yy, y, "y", "rowStride", "0", "maxY"));
123
+ }
124
+ }
125
+ const decls = isPool ? "" : `const [${kvars.join(", ")}] = [${tpl.join(", ")}];`;
126
+ const inner = isPool ? tpl(body, w, h) : body.join(" + ");
127
+ const fnBody = [
128
+ decls,
129
+ "const { min, max } = Math;",
130
+ "const { data: pix, stride: [stride, rowStride] } = src;",
131
+ "const maxX = (src.width - 1) * stride;",
132
+ "const maxY = (src.height - 1) * rowStride;",
133
+ "return (x, y, channel) => {",
134
+ ...prefix,
135
+ `return ${inner};`,
136
+ "}"
137
+ ].join("\n");
138
+ return new Function("src", fnBody);
139
+ };
140
+ const defLargeKernel = (kernel, w, h, normalize = false) => {
141
+ if (normalize) kernel = __normalize(kernel);
142
+ return (src) => {
143
+ const {
144
+ data,
145
+ stride: [stride, rowStride]
146
+ } = src;
147
+ const x0 = -(w >> 1) * stride;
148
+ const x1 = -x0 + (w & 1 ? stride : 0);
149
+ const y0 = -(h >> 1) * rowStride;
150
+ const y1 = -y0 + (h & 1 ? rowStride : 0);
151
+ const maxX = (src.width - 1) * stride;
152
+ const maxY = (src.height - 1) * rowStride;
153
+ return (xx, yy, channel) => {
154
+ const $maxX = maxX + channel;
155
+ let sum = 0, y, x, k, row;
156
+ for (y = y0, k = 0; y < y1; y += rowStride) {
157
+ for (x = x0, row = clamp(yy + y, 0, maxY); x < x1; x += stride, k++) {
158
+ sum += kernel[k] * data[row + clamp(xx + x, channel, $maxX)];
159
+ }
160
+ }
161
+ return sum;
162
+ };
163
+ };
164
+ };
165
+ const __normalize = (kernel) => {
166
+ const scale = 1 / kernel.reduce((acc, x) => acc + x, 0);
167
+ return kernel.map((x) => x * scale);
168
+ };
169
+ const POOL_NEAREST = (body, w, h) => body[(h >> 1) * w + (w >> 1)];
170
+ const POOL_MEAN = (body, w, h) => `(${body.join("+")})*${1 / (w * h)}`;
171
+ const POOL_MIN = (body) => `Math.min(${body.join(",")})`;
172
+ const POOL_MAX = (body) => `Math.max(${body.join(",")})`;
173
+ const POOL_THRESHOLD = (bias = 0) => (body, w, h) => {
174
+ const center = POOL_NEAREST(body, w, h);
175
+ const mean = `(${body.join("+")})/${w * h}`;
176
+ return `(${center} - ${mean} + ${bias}) < 0 ? 0 : 1`;
177
+ };
178
+ const SOBEL_X = {
179
+ spec: [-1, -2, -1, 0, 0, 0, 1, 2, 1],
180
+ size: 3
181
+ };
182
+ const SOBEL_Y = {
183
+ spec: [-1, 0, 1, -2, 0, 2, -1, 0, 1],
184
+ size: 3
185
+ };
186
+ const SHARPEN3 = {
187
+ spec: [0, -1, 0, -1, 5, -1, 0, -1, 0],
188
+ size: 3
189
+ };
190
+ const HIGHPASS3 = {
191
+ spec: [-1, -1, -1, -1, 9, -1, -1, -1, -1],
192
+ size: 3
193
+ };
194
+ const BOX_BLUR3 = {
195
+ pool: POOL_MEAN,
196
+ size: 3
197
+ };
198
+ const BOX_BLUR5 = {
199
+ pool: POOL_MEAN,
200
+ size: 5
201
+ };
202
+ const GAUSSIAN_BLUR3 = {
203
+ spec: [1 / 16, 1 / 8, 1 / 16, 1 / 8, 1 / 4, 1 / 8, 1 / 16, 1 / 8, 1 / 16],
204
+ size: 3
205
+ };
206
+ const GAUSSIAN_BLUR5 = {
207
+ // prettier-ignore
208
+ spec: [
209
+ 1 / 256,
210
+ 1 / 64,
211
+ 3 / 128,
212
+ 1 / 64,
213
+ 1 / 256,
214
+ 1 / 64,
215
+ 1 / 16,
216
+ 3 / 32,
217
+ 1 / 16,
218
+ 1 / 64,
219
+ 3 / 128,
220
+ 3 / 32,
221
+ 9 / 64,
222
+ 3 / 32,
223
+ 3 / 128,
224
+ 1 / 64,
225
+ 1 / 16,
226
+ 3 / 32,
227
+ 1 / 16,
228
+ 1 / 64,
229
+ 1 / 256,
230
+ 1 / 64,
231
+ 3 / 128,
232
+ 1 / 64,
233
+ 1 / 256
234
+ ],
235
+ size: 5
236
+ };
237
+ const GAUSSIAN = (r) => {
238
+ r |= 0;
239
+ assert(r > 0, `invalid kernel radius: ${r}`);
240
+ const sigma = -1 / (2 * (Math.hypot(r, r) / 3) ** 2);
241
+ const res = [];
242
+ let sum = 0;
243
+ for (let y = -r; y <= r; y++) {
244
+ for (let x = -r; x <= r; x++) {
245
+ const g = Math.exp((x * x + y * y) * sigma);
246
+ res.push(g);
247
+ sum += g;
248
+ }
249
+ }
250
+ return { spec: res.map((x) => x / sum), size: r * 2 + 1 };
251
+ };
252
+ const LANCZOS = (a, scale = 2) => {
253
+ assert(a > 0, `invalid coefficient: ${a}`);
254
+ const r = Math.ceil(a * scale);
255
+ const res = [];
256
+ let sum = 0;
257
+ for (let y = -r; y <= r; y++) {
258
+ const yy = y / scale;
259
+ const ly = lanczos(a, yy);
260
+ for (let x = -r; x <= r; x++) {
261
+ const m = Math.hypot(x / scale, yy);
262
+ const l = m < a ? ly * lanczos(a, x / scale) : 0;
263
+ res.push(l);
264
+ sum += l;
265
+ }
266
+ }
267
+ return { spec: res.map((x) => x / sum), size: r * 2 + 1 };
268
+ };
269
+ const UNSHARP_MASK5 = {
270
+ // prettier-ignore
271
+ spec: [
272
+ -1 / 256,
273
+ -1 / 64,
274
+ -3 / 128,
275
+ -1 / 64,
276
+ -1 / 256,
277
+ -1 / 64,
278
+ -1 / 16,
279
+ -3 / 32,
280
+ -1 / 16,
281
+ -1 / 64,
282
+ -3 / 128,
283
+ -3 / 32,
284
+ 119 / 64,
285
+ -3 / 32,
286
+ -3 / 128,
287
+ -1 / 64,
288
+ -1 / 16,
289
+ -3 / 32,
290
+ -1 / 16,
291
+ -1 / 64,
292
+ -1 / 256,
293
+ -1 / 64,
294
+ -3 / 128,
295
+ -1 / 64,
296
+ -1 / 256
297
+ ],
298
+ size: 5
299
+ };
300
+ const { min, max } = Math;
301
+ const MAXIMA4_CROSS = {
302
+ fn: (src) => {
303
+ const {
304
+ data: pix,
305
+ stride: [stride, rowStride]
306
+ } = src;
307
+ const maxX = (src.width - 1) * stride;
308
+ const maxY = (src.height - 1) * rowStride;
309
+ return (x, y, channel) => {
310
+ const x0 = max(x - stride, channel);
311
+ const x2 = min(x + stride, maxX + channel);
312
+ const y0 = max(y - rowStride, 0);
313
+ const y2 = min(y + rowStride, maxY);
314
+ const c = pix[x + y];
315
+ return c > pix[y + x0] && c > pix[y + x2] || c > pix[y0 + x] && c > pix[y2 + x] ? 1 : 0;
316
+ };
317
+ },
318
+ size: 3
319
+ };
320
+ const MAXIMA4_DIAG = {
321
+ fn: (src) => {
322
+ const {
323
+ data: pix,
324
+ stride: [stride, rowStride]
325
+ } = src;
326
+ const maxX = (src.width - 1) * stride;
327
+ const maxY = (src.height - 1) * rowStride;
328
+ return (x, y, channel) => {
329
+ const x0 = max(x - stride, channel);
330
+ const x2 = min(x + stride, maxX + channel);
331
+ const y0 = max(y - rowStride, 0);
332
+ const y2 = min(y + rowStride, maxY);
333
+ const c = pix[x + y];
334
+ return c > pix[y0 + x0] && c > pix[y2 + x2] || c > pix[y0 + x2] && c > pix[y2 + x0] ? 1 : 0;
335
+ };
336
+ },
337
+ size: 3
338
+ };
339
+ const MAXIMA8 = {
340
+ fn: (src) => {
341
+ const {
342
+ data: pix,
343
+ stride: [stride, rowStride]
344
+ } = src;
345
+ const maxX = (src.width - 1) * stride;
346
+ const maxY = (src.height - 1) * rowStride;
347
+ return (x, y, channel) => {
348
+ const x0 = max(x - stride, channel);
349
+ const x2 = min(x + stride, maxX + channel);
350
+ const y0 = max(y - rowStride, 0);
351
+ const y2 = min(y + rowStride, maxY);
352
+ const c = pix[x + y];
353
+ return c > pix[y + x0] && c > pix[y + x2] || c > pix[y0 + x] && c > pix[y2 + x] || c > pix[y0 + x0] && c > pix[y2 + x2] || c > pix[y0 + x2] && c > pix[y2 + x0] ? 1 : 0;
354
+ };
355
+ },
356
+ size: 3
357
+ };
358
+ export {
359
+ BOX_BLUR3,
360
+ BOX_BLUR5,
361
+ GAUSSIAN,
362
+ GAUSSIAN_BLUR3,
363
+ GAUSSIAN_BLUR5,
364
+ HIGHPASS3,
365
+ LANCZOS,
366
+ MAXIMA4_CROSS,
367
+ MAXIMA4_DIAG,
368
+ MAXIMA8,
369
+ POOL_MAX,
370
+ POOL_MEAN,
371
+ POOL_MIN,
372
+ POOL_NEAREST,
373
+ POOL_THRESHOLD,
374
+ SHARPEN3,
375
+ SOBEL_X,
376
+ SOBEL_Y,
377
+ UNSHARP_MASK5,
378
+ convolveChannel,
379
+ convolveImage,
380
+ defKernel,
381
+ defLargeKernel
382
+ };
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./api.js";
2
+ export * from "./convolve.js";
3
+ export * from "./normal-map.js";
4
+ export * from "./pyramid.js";
5
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./api.js";
2
+ export * from "./convolve.js";
3
+ export * from "./normal-map.js";
4
+ export * from "./pyramid.js";
@@ -0,0 +1,22 @@
1
+ import { FloatBuffer } from "@thi.ng/pixel/float";
2
+ import type { NormalMapOpts } from "./api.js";
3
+ /**
4
+ * Computes normal map image (aka gradient in X & Y directions and a static Z
5
+ * value) for a single channel in given {@link FloatBuffer}. The resulting
6
+ * buffer will use the {@link FLOAT_NORMAL} format, storing the horizontal
7
+ * gradient in the 1st channel (red), vertical gradient in the 2nd channel
8
+ * (green) and sets last channel to given `z` value (blue).
9
+ *
10
+ * @remarks
11
+ * The gradient values will be scaled with `scale` (default: 1, but supports
12
+ * individual X/Y factors). Gradient values will be signed.
13
+ *
14
+ * The partial gradients of the last column/row will be set to zero
15
+ * (respectively). I.e. the right most pixel column will have `red = 0` and last
16
+ * row will have `green = 0`.
17
+ *
18
+ * @param src -
19
+ * @param opts -
20
+ */
21
+ export declare const normalMap: (src: FloatBuffer, opts?: Partial<NormalMapOpts>) => FloatBuffer;
22
+ //# sourceMappingURL=normal-map.d.ts.map
package/normal-map.js ADDED
@@ -0,0 +1,33 @@
1
+ import { ensureChannel } from "@thi.ng/pixel/checks";
2
+ import { FloatBuffer } from "@thi.ng/pixel/float";
3
+ import { FLOAT_NORMAL } from "@thi.ng/pixel/format/float-norm";
4
+ import { __asVec } from "@thi.ng/pixel/internal/utils";
5
+ import { convolveChannel } from "./convolve.js";
6
+ const normalMap = (src, opts = {}) => {
7
+ const { channel = 0, step = 0, scale = 1, z = 1 } = opts;
8
+ ensureChannel(src.format, channel);
9
+ const spec = [-1, ...new Array(step).fill(0), 1];
10
+ const [sx, sy] = __asVec(scale);
11
+ const dest = new FloatBuffer(src.width, src.height, FLOAT_NORMAL);
12
+ dest.setChannel(
13
+ 0,
14
+ convolveChannel(src, {
15
+ kernel: { spec, size: [step + 2, 1] },
16
+ scale: sx,
17
+ channel
18
+ })
19
+ );
20
+ dest.setChannel(
21
+ 1,
22
+ convolveChannel(src, {
23
+ kernel: { spec, size: [1, step + 2] },
24
+ scale: sy,
25
+ channel
26
+ })
27
+ );
28
+ dest.setChannel(2, z);
29
+ return dest;
30
+ };
31
+ export {
32
+ normalMap
33
+ };
package/package.json ADDED
@@ -0,0 +1,104 @@
1
+ {
2
+ "name": "@thi.ng/pixel-convolve",
3
+ "version": "0.1.0",
4
+ "description": "Extensible bitmap image convolution, kernel presets, normal map & image pyramid generation",
5
+ "type": "module",
6
+ "module": "./index.js",
7
+ "typings": "./index.d.ts",
8
+ "sideEffects": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/thi-ng/umbrella.git"
12
+ },
13
+ "homepage": "https://thi.ng/pixel-convolve",
14
+ "funding": [
15
+ {
16
+ "type": "github",
17
+ "url": "https://github.com/sponsors/postspectacular"
18
+ },
19
+ {
20
+ "type": "patreon",
21
+ "url": "https://patreon.com/thing_umbrella"
22
+ }
23
+ ],
24
+ "author": "Karsten Schmidt (https://thi.ng)",
25
+ "license": "Apache-2.0",
26
+ "scripts": {
27
+ "build": "yarn build:esbuild && yarn build:decl",
28
+ "build:decl": "tsc --declaration --emitDeclarationOnly",
29
+ "build:esbuild": "esbuild --format=esm --platform=neutral --target=es2022 --tsconfig=tsconfig.json --outdir=. src/**/*.ts",
30
+ "clean": "bun ../../tools/src/clean-package.ts",
31
+ "doc": "typedoc --excludePrivate --excludeInternal --out doc src/index.ts",
32
+ "doc:ae": "mkdir -p .ae/doc .ae/temp && api-extractor run --local --verbose",
33
+ "doc:readme": "bun ../../tools/src/module-stats.ts && bun ../../tools/src/readme.ts",
34
+ "pub": "yarn npm publish --access public",
35
+ "test": "bun test",
36
+ "tool:tangle": "../../node_modules/.bin/tangle src/**/*.ts"
37
+ },
38
+ "dependencies": {
39
+ "@thi.ng/api": "^8.11.7",
40
+ "@thi.ng/checks": "^3.6.9",
41
+ "@thi.ng/errors": "^2.5.13",
42
+ "@thi.ng/math": "^5.11.5",
43
+ "@thi.ng/pixel": "^7.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@microsoft/api-extractor": "^7.47.0",
47
+ "esbuild": "^0.23.0",
48
+ "typedoc": "^0.26.3",
49
+ "typescript": "^5.5.3"
50
+ },
51
+ "keywords": [
52
+ "blur",
53
+ "channel",
54
+ "convolution",
55
+ "edge",
56
+ "float",
57
+ "gaussian",
58
+ "mean",
59
+ "normal",
60
+ "pixel",
61
+ "pool",
62
+ "pyramid",
63
+ "resize",
64
+ "sample",
65
+ "sharpen",
66
+ "typescript"
67
+ ],
68
+ "publishConfig": {
69
+ "access": "public"
70
+ },
71
+ "browser": {
72
+ "process": false,
73
+ "setTimeout": false
74
+ },
75
+ "engines": {
76
+ "node": ">=18"
77
+ },
78
+ "files": [
79
+ "./*.js",
80
+ "./*.d.ts"
81
+ ],
82
+ "exports": {
83
+ ".": {
84
+ "default": "./index.js"
85
+ },
86
+ "./api": {
87
+ "default": "./api.js"
88
+ },
89
+ "./convolve": {
90
+ "default": "./convolve.js"
91
+ },
92
+ "./normal-map": {
93
+ "default": "./normal-map.js"
94
+ },
95
+ "./pyramid": {
96
+ "default": "./pyramid.js"
97
+ }
98
+ },
99
+ "thi.ng": {
100
+ "parent": "@thi.ng/pixel",
101
+ "year": 2021
102
+ },
103
+ "gitHead": "324d6b7dbf31558329e9fb6452e29b2f7db9c61a\n"
104
+ }
package/pyramid.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { FloatBuffer } from "@thi.ng/pixel/float";
2
+ import type { KernelSpec } from "./api.js";
3
+ /**
4
+ * Yields an iterator of progressively downsampled versions of `src` (using
5
+ * `kernel` for filtering, default: {@link LANCZOS}(2)). Each image will be half
6
+ * size of the previous result, stopping only once either width or height
7
+ * becomes less than `minSize` (default: 1). If `includeOrig` is enabled
8
+ * (default), the first emitted image will be the original `src`.
9
+ *
10
+ * @param src -
11
+ * @param kernel -
12
+ * @param minSize -
13
+ * @param includeOrig -
14
+ */
15
+ export declare function imagePyramid(src: FloatBuffer, kernel?: KernelSpec, minSize?: number, includeOrig?: boolean): Generator<FloatBuffer, void, unknown>;
16
+ //# sourceMappingURL=pyramid.d.ts.map
package/pyramid.js ADDED
@@ -0,0 +1,14 @@
1
+ import { assert } from "@thi.ng/errors/assert";
2
+ import { convolveImage, LANCZOS } from "./convolve.js";
3
+ function* imagePyramid(src, kernel = LANCZOS(2), minSize = 1, includeOrig = true) {
4
+ assert(minSize > 0, `invalid min size`);
5
+ minSize <<= 1;
6
+ if (includeOrig) yield src;
7
+ while (src.width >= minSize && src.height >= minSize) {
8
+ src = convolveImage(src, { kernel, stride: 2 });
9
+ yield src;
10
+ }
11
+ }
12
+ export {
13
+ imagePyramid
14
+ };