diff --git a/.clang-format b/.clang-format
new file mode 100644
index 000000000..5e7a0eb82
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,4 @@
+BasedOnStyle: Google
+IndentWidth: 4
+ColumnLimit: 100
+AllowShortFunctionsOnASingleLine: false
diff --git a/.editorconfig b/.editorconfig
index 998c7dc75..4ce5fcbc1 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -15,9 +15,9 @@ max_line_length = 120
# -------------------------
# C++ / C headers
# -------------------------
-[*.{cpp,h}]
+[*.{hpp,cpp,c,h}]
indent_style = space
-indent_size = 2
+indent_size = 4
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
new file mode 100644
index 000000000..b0aef78b5
--- /dev/null
+++ b/.github/workflows/build-docs.yml
@@ -0,0 +1,40 @@
+name: Build Documentation
+
+on:
+ workflow_call:
+ secrets:
+ ALGOLIA_APP_ID:
+ required: true
+ ALGOLIA_API_KEY:
+ required: true
+ ALGOLIA_INDEX_NAME:
+ required: true
+
+permissions:
+ contents: read
+
+jobs:
+ build-docs:
+ name: Build Docusaurus Site
+ runs-on: ubuntu-latest
+ container:
+ image: ryanmillard/img2num-dev:latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Install Dependendencies
+ run: pnpm --filter docs install
+
+ - name: Build Docusaurus
+ env:
+ ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }}
+ ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }}
+ ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }}
+ run: pnpm -F docs run build
+
+ - name: Upload Documentation Artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: docs-build
+ path: docs/build
diff --git a/.github/workflows/build-react-app.yml b/.github/workflows/build-react-app.yml
new file mode 100644
index 000000000..3a517fe16
--- /dev/null
+++ b/.github/workflows/build-react-app.yml
@@ -0,0 +1,40 @@
+name: Build React App
+
+on:
+ workflow_call:
+ inputs:
+ wasm-artifacts-path:
+ required: false
+ type: string
+
+permissions:
+ contents: read
+
+jobs:
+ build-react-app:
+ name: Build React Example App
+ runs-on: ubuntu-latest
+ container:
+ image: ryanmillard/img2num-dev:latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Install Dependendencies
+ run: pnpm --filter react-example install
+
+ - name: Download WASM artifacts
+ if: ${{ inputs.wasm-artifacts-path }}
+ uses: actions/download-artifact@v4
+ with:
+ name: wasm-build
+ path: ${{ inputs.wasm-artifacts-path }}
+
+ - name: Build React app
+ run: pnpm -F react-example run build
+
+ - name: Upload React build artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: react-build
+ path: example-apps/react-js/dist/
diff --git a/.github/workflows/build-wasm.yml b/.github/workflows/build-wasm.yml
new file mode 100644
index 000000000..719e8c705
--- /dev/null
+++ b/.github/workflows/build-wasm.yml
@@ -0,0 +1,29 @@
+name: Build WASM
+
+on:
+ workflow_call:
+
+permissions:
+ contents: read
+
+jobs:
+ build-wasm:
+ name: Build C++ (Emscripten)
+ runs-on: ubuntu-latest
+ container:
+ image: ryanmillard/img2num-dev:latest
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Run emcmake
+ run: emcmake cmake -B build-wasm/ .
+
+ - name: Build using Emscripten
+ run: cmake --build build-wasm/
+
+ - name: Upload WASM build artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: wasm-build
+ path: packages/js/build-wasm/
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 65ebea142..693c85f96 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,95 +6,50 @@ on:
push:
branches: [main]
+permissions:
+ contents: read
+
jobs:
lint:
- name: Lint Code
+ name: Lint & Validate Code
runs-on: ubuntu-latest
+ container:
+ image: ryanmillard/img2num-dev:latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- - name: Setup Node.js
- uses: actions/setup-node@v6
- with:
- node-version: "22"
- cache: "npm"
-
- - name: Install dependencies
- run: npm ci
+ - name: Install PNPM dependencies
+ run: pnpm install
- name: Run ESLint
- run: npm run lint
-
- - name: Run format check
- run: npm run format:check
-
- - name: Run editorconfig-checker
- run: npm run lint:style
- validate-scripts:
- runs-on: ubuntu-latest
- steps:
- # Checkout full history to ensure git diff works
- - uses: actions/checkout@v6
- with:
- fetch-depth: 0
- # Node.js setup
- - name: Setup Node.js
- uses: actions/setup-node@v6
- with:
- node-version: 22
- # Install dependencies
- - name: Install dependencies
- run: npm ci
- # Detect if scripts changed
- - name: Determine if scripts changed
- id: check_changes
- shell: bash
- run: |
- echo "Checking for changed scripts..."
- if [[ "${{ github.event_name }}" == "pull_request" ]]; then
- BASE_SHA="${{ github.event.pull_request.base.sha }}"
- else
- BASE_SHA="${{ github.event.before }}"
- fi
- HEAD_SHA="${{ github.sha }}"
- # Ensure a valid common ancestor (handles force-pushes)
- BASE_SHA=$(git merge-base "$BASE_SHA" "$HEAD_SHA")
- files=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA")
- echo "Changed files: $files"
- match=false
- for file in $files; do
- if [[ "$file" == "package.json" || "$file" == "docs/package.json" ]]; then
- if git diff "$BASE_SHA" "$HEAD_SHA" -- "$file" | grep -q '"scriptsInfo"'; then
- match=true
- break
- fi
- elif [[ "$file" == scripts/* || "$file" == docs/scripts/* ]]; then
- match=true
- break
- fi
- done
- echo "scripts_changed=$match" >> "$GITHUB_OUTPUT"
- # Run script validation if scripts changed
- - name: Run script validation
- id: validate
- if: steps.check_changes.outputs.scripts_changed == 'true'
- shell: bash
- run: |
- set -o pipefail
- npm run validate-scripts 2>&1 | tee validation.log
- echo "validation_exit_code=${PIPESTATUS[0]}" >> $GITHUB_OUTPUT
- # Comment on PR if validation fails
- - name: Comment on PR if validation fails
- if: steps.validate.outputs.validation_exit_code != '0' && github.event_name == 'pull_request'
- uses: ./.github/workflows/commenter.yml
- with:
- issue_number: ${{ github.event.pull_request.number }}
- message: |
- ⚠️ **Script validation failed!**
- The following issues were found with your PR (latest 100 lines):
- ```
- $(tail -n 100 validation.log)
- ```
- is_pr: true
+ run: pnpm run eslint
+
+ - name: Validate format
+ run: pnpm run format:check
+
+ - name: Validate .editorconfig adherance
+ run: pnpm run editorconfig:check
+
+ - name: Validate scriptsInfo in package.json
+ run: pnpm run validate-scripts
+
+ build-wasm:
+ name: Build WASM
+ uses: ./.github/workflows/build-wasm.yml
+
+ build-react-app:
+ name: Build React App
+ uses: ./.github/workflows/build-react-app.yml
+ needs: build-wasm
+ with:
+ wasm-artifacts-path: packages/js/build-wasm/
+
+ build-docs:
+ name: Build Documentation Site
+ uses: ./.github/workflows/build-docs.yml
+ secrets:
+ ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }}
+ ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }}
+ ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }}
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index d96ceaabe..ab29aa731 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -5,59 +5,64 @@ on:
branches:
- main
+permissions:
+ contents: write
+
jobs:
- build-and-deploy:
- runs-on: ubuntu-latest
+ build-wasm:
+ name: Build WASM
+ uses: ./.github/workflows/build-wasm.yml
+
+ build-react-app:
+ name: Build React App
+ uses: ./.github/workflows/build-react-app.yml
+ needs: build-wasm
+ with:
+ wasm-artifacts-path: packages/js/build-wasm/
+
+ build-docs:
+ name: Build Documentation Site
+ uses: ./.github/workflows/build-docs.yml
+ secrets:
+ ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }}
+ ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }}
+ ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }}
+ deploy-react-app:
+ name: Deploy React App to GitHub Pages
+ needs: build-react-app
+ runs-on: ubuntu-latest
steps:
- - name: Checkout repository
- uses: actions/checkout@v6
+ - name: Download React build artifacts
+ uses: actions/download-artifact@v4
+ with:
+ name: react-build
+ path: ./react-dist
+
+ - name: Deploy React App
+ uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e
+ with:
+ github_token: ${{ secrets.GITHUB_TOKEN }}
+ publish_dir: ./react-dist
+ user_name: "github-actions[bot]"
+ user_email: "github-actions[bot]@users.noreply.github.com"
- - name: Setup Node.js
- uses: actions/setup-node@v6
+ deploy-docs:
+ name: Deploy Documentation to GitHub Pages
+ needs: build-docs
+ runs-on: ubuntu-latest
+ steps:
+ - name: Download Docs build artifacts
+ uses: actions/download-artifact@v4
with:
- node-version: 20
-
- - name: Install npm dependencies
- run: npm ci
-
- - name: Install Emscripten SDK
- run: |
- # Download and extract EMSDK
- curl -sSL https://github.com/emscripten-core/emsdk/archive/refs/tags/4.0.15.tar.gz | tar -xz
- cd emsdk-4.0.15
- ./emsdk install latest
- ./emsdk activate latest
-
- # Source into this shell so the build here works
- source ./emsdk_env.sh
-
- # Persist variables for later steps
- echo "EMSDK=${GITHUB_WORKSPACE}/emsdk-4.0.15" >> $GITHUB_ENV
- echo "EMSDK_NODE=${GITHUB_WORKSPACE}/emsdk-4.0.15/node/22.16.0_64bit/bin/node" >> $GITHUB_ENV
- echo "PATH=${GITHUB_WORKSPACE}/emsdk-4.0.15:${GITHUB_WORKSPACE}/emsdk-4.0.15/upstream/emscripten:$PATH" >> $GITHUB_ENV
-
- - name: Build Vite app
- run: npm run build
-
- - name: Build Docusaurus site
- env:
- ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }}
- ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }}
- ALGOLIA_INDEX_NAME: ${{ secrets.ALGOLIA_INDEX_NAME }}
- run: |
- cd docs
- npm ci
- npm run build
- cd ..
- mkdir -p dist/info
- cp -r docs/build/* dist/info/
- shell: bash
-
- - name: Deploy everything to GitHub Pages
- uses: peaceiris/actions-gh-pages@v4
+ name: docs-build
+ path: ./docs-dist
+
+ - name: Deploy Documentation
+ uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
- publish_dir: ./dist
+ publish_dir: ./docs-dist
+ destination_dir: info
user_name: "github-actions[bot]"
user_email: "github-actions[bot]@users.noreply.github.com"
diff --git a/.gitignore b/.gitignore
index 337a18a47..76e57fda2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,15 @@
+# pnpm
+node_modules/
+.pnpm-store/
+
+# cmake
+build-wasm/
+
+build*/
+
# Logs
logs
*.log
-npm-debug.log*
-yarn-debug.log*
-yarn-error.log*
-pnpm-debug.log*
-lerna-debug.log*
-
-node_modules
-dist
-dist-ssr
*.local
# Editor directories and files
@@ -26,10 +26,4 @@ dist-ssr
# OS Files
*:Zone.Identifier
-src/data/contributor-credits.json
-
.env
-# CMake build artifacts
-src/wasm/cmake-build/
-src/wasm/**/CMakeCache.txt
-src/wasm/**/CMakeFiles/
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 000000000..73375d171
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1,4 @@
+package-manager=pnpm
+engine-strict=true
+auto-install-peers=false
+strict-peer-dependencies=true
diff --git a/.prettierignore b/.prettierignore
index 1b8ac8894..f839bdf2c 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -1,3 +1,33 @@
-# Ignore artifacts:
-build
-coverage
+packages/js/build-wasm
+docs/.docusaurus
+docs/build/
+example-apps/react-js/dist/
+.clang-format
+.devcontainer
+.dockerignore
+.editorconfig
+.git/
+.gitattributes
+.github/
+.gitignore
+.prettierignore
+.prettierrc
+CMakeLists.txt
+CODE_OF_CONDUCT.md
+CONTRIBUTING.md
+Dockerfile.dev
+README.md
+bindings/
+build*/
+core/
+docker-compose.yml
+img2num
+img2num.bat
+img2num.ps1
+node_modules/
+scripts/
+pnpm-lock.yaml
+.pnpm-store/
+docs/static/js/api.json
+docs/docs/js/api/
+example-apps/react-js/src/data/contributor-credits.json
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 000000000..ab423d751
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,19 @@
+# =================================================================
+# Img2Num Top-Level
+# =================================================================
+cmake_minimum_required(VERSION 3.16)
+project(Img2Num LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+# Default build type
+if(NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
+endif()
+
+# Core library
+add_subdirectory(core)
+
+# JS bindings
+add_subdirectory(bindings/js)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ede3fd587..60188d1a9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,39 +2,15 @@
Want to contribute to Img2Num? There are a few things you need to know.
-We wrote a [contribution guide](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/contributing) to help you get started.
+We wrote a [contribution guide](https://ryan-millard.github.io/Img2Num/info/docs/contributing) to help you get started.
-## Quick Links
+**A few important points:**
-- **[Coding Style Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/coding-style)** - Code quality and linting standards
-- **[CI/CD Workflows](https://ryan-millard.github.io/Img2Num/info/docs/reference/tools/ci-workflows)** - Understanding our automated checks
-- **[Commit Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/commits)** - How to write good commit messages
-- **[Pull Request Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/pull-requests)** - Creating and submitting PRs
+- **Add tests** with your PR — new features and bug fixes **must** include tests where appropriate. PRs without tests are unlikely to be approved.
+- Follow the repository's coding style rules.
+- Use the issue and PR templates when filing issues or submitting code. Your PR will be rejected if you don't.
-## Code Quality
-
-Before submitting a PR, ensure your code passes all checks:
-
-**With Docker:**
-
-```bash
-./img2num npm ci # Install dependencies
-./img2num lint # Check JavaScript/React code
-./img2num lint:style # Check code style
-./img2num npm run format:check # Verify formatting
-```
-
-**Local Dev:**
-
-```bash
-npm ci # Install dependencies
-npm run lint # Check JavaScript/React code
-npm run lint:style # Check code style
-npm run format:check # Verify formatting
-```
-
-For detailed information about linting, formatting, and fixing issues, see our
-[Coding Style Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/coding-style).
+If you're unsure what to change, [open a discussion](https://github.com/Ryan-Millard/Img2Num/discussions/new/choose) and someone will assist you.
## Questions?
@@ -42,6 +18,6 @@ If you have questions or need help:
- Open a [discussion](https://github.com/Ryan-Millard/Img2Num/discussions)
- Create an [issue](https://github.com/Ryan-Millard/Img2Num/issues)
-- Check existing PRs for examples
+- Check existing PRs for ideas
Thank you for improving Img2Num! 🎨🚀
diff --git a/Dockerfile.dev b/Dockerfile.dev
index 02474aa9b..5809718f3 100644
--- a/Dockerfile.dev
+++ b/Dockerfile.dev
@@ -6,31 +6,39 @@ FROM node:22-bullseye
ENV EMSDK_VERSION=4.0.10
ENV EMSDK_DIR=/opt/emsdk
-RUN apt-get update && apt-get install -y --no-install-recommends \
- build-essential \
- cmake \
- python3 \
- git \
- curl \
- unzip \
- pkg-config \
- bash \
- ca-certificates \
- libvips-dev \
- && rm -rf /var/lib/apt/lists/*
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends \
+ build-essential \
+ cmake \
+ python3 \
+ git \
+ curl \
+ unzip \
+ pkg-config \
+ bash \
+ ca-certificates \
+ libvips-dev \
+ # graphviz enables diagrams in doxygen
+ doxygen graphviz \
+ && rm -rf /var/lib/apt/lists/*
# Install EMSDK once, cached by Docker layers
RUN git clone --depth 1 https://github.com/emscripten-core/emsdk.git $EMSDK_DIR \
-&& cd $EMSDK_DIR \
-&& git fetch --tags \
-&& git checkout $EMSDK_VERSION \
-&& ./emsdk install $EMSDK_VERSION \
-&& ./emsdk activate $EMSDK_VERSION
-
+ && cd $EMSDK_DIR \
+ && git fetch --tags \
+ && git checkout $EMSDK_VERSION \
+ && ./emsdk install $EMSDK_VERSION \
+ && ./emsdk activate $EMSDK_VERSION
ENV PATH=$EMSDK_DIR:$EMSDK_DIR/upstream/emscripten:$PATH
ENV EMSDK=$EMSDK_DIR
-RUN npm install -g npm@11
+# Install pnpm
+RUN corepack enable \
+ && corepack prepare pnpm@10.29.1 --activate
+
+# Corepack installs pnpm here for root
+ENV PATH=/root/.local/share/pnpm:$PATH
+ENV PNPM_STORE_DIR=/pnpm/store
WORKDIR /usr/src/app
diff --git a/LICENSE b/LICENSE
index 0ad25db4b..e13386ce9 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,661 +1,14 @@
- GNU AFFERO GENERAL PUBLIC LICENSE
- Version 3, 19 November 2007
+Licensing
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
+This project is **primarily licensed under the MIT License** (see https://github.com/Ryan-Millard/Img2Num/blob/main/LICENSE-MIT).
- Preamble
+Certain files and folders remain licensed under the **GNU AGPLv3** (see https://github.com/Ryan-Millard/Img2Num/blob/main/LICENSE-AGPL):
+- `example-apps/react-js/` (consumer example application built in React)
+- `docs/` (project documentation)
+- `.github/` (CI/config files)
- The GNU Affero General Public License is a free, copyleft license for
-software and other kinds of works, specifically designed to ensure
-cooperation with the community in the case of network server software.
+These AGPL-licensed files **do not affect the use or redistribution of the MIT-licensed packages**.
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-our General Public Licenses are intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.
+This is because the project was originally licensed under the GNU AGPLv3.
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- Developers that use our General Public Licenses protect your rights
-with two steps: (1) assert copyright on the software, and (2) offer
-you this License which gives you legal permission to copy, distribute
-and/or modify the software.
-
- A secondary benefit of defending all users' freedom is that
-improvements made in alternate versions of the program, if they
-receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
-software used on network servers, this result may fail to come about.
-The GNU General Public License permits making a modified version and
-letting the public access it on a server without ever releasing its
-source code to the public.
-
- The GNU Affero General Public License is designed specifically to
-ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
-provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
-a publicly accessible server, gives the public access to the source
-code of the modified version.
-
- An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
-a different license, not a version of the Affero GPL, but Affero has
-released a new version of the Affero GPL which permits relicensing under
-this license.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU Affero General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Remote Network Interaction; Use with the GNU General Public License.
-
- Notwithstanding any other provision of this License, if you modify the
-Program, your modified version must prominently offer all users
-interacting with it remotely through a computer network (if your version
-supports such interaction) an opportunity to receive the Corresponding
-Source of your version by providing access to the Corresponding Source
-from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
-shall include the Corresponding Source for any work covered by version 3
-of the GNU General Public License that is incorporated pursuant to the
-following paragraph.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the work with which it is combined will remain governed by version
-3 of the GNU General Public License.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
-will be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU Affero General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU Affero General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU Affero General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published
- by the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If your software can interact with users remotely through a computer
-network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
-interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
-solutions will be better for different programs; see section 13 for the
-specific requirements.
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU AGPL, see
-.
+Approval for relicensing the bulk of the project under MIT was granted by the relevant contributors in GitHub Discussion #230 (see https://github.com/Ryan-Millard/Img2Num/discussions/230).
diff --git a/docs/docs/introduction/license.md b/LICENSE-AGPL
similarity index 99%
rename from docs/docs/introduction/license.md
rename to LICENSE-AGPL
index 773e9fd51..d6f45c602 100644
--- a/docs/docs/introduction/license.md
+++ b/LICENSE-AGPL
@@ -1,10 +1,5 @@
----
-id: license
-title: License
-sidebar_position: 2
----
+Note: This project also contains MIT-licensed files (core packages, scripts, libraries). See top-level LICENSE file for details.
-```
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
@@ -666,4 +661,3 @@ specific requirements.
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
-```
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 000000000..7bec07222
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,23 @@
+Note: This project also contains AGPL-licensed files (docs, React example app, CI/config). See top-level LICENSE file for details.
+
+MIT License
+
+Copyright (c) 2026 Ryan Millard
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 54af79dc5..709a5d765 100644
--- a/README.md
+++ b/README.md
@@ -4,9 +4,7 @@
# Img2Num
-[](https://ryan-millard.github.io/Img2Num/)
-[](https://ryan-millard.github.io/Img2Num/info/)
-[](LICENSE)
+[](https://github.com/Ryan-Millard/Img2Num/actions/workflows/deploy.yml)
@@ -61,9 +59,6 @@ Try it out now by [clicking here](https://ryan-millard.github.io/Img2Num/)!
---
-> [!IMPORTANT]
-> We're in the process of converting the C++ into a self-contained library that is separate from the React app. Stay tuned by watching this repo!
-
## What this repository contains (short)
- A React frontend that handles image input, preview and in-browser colouring.
@@ -71,31 +66,26 @@ Try it out now by [clicking here](https://ryan-millard.github.io/Img2Num/)!
This README is intentionally short — full installation steps, guides and references live in the docs site (see **Essential links** below).
-## Essential links (docs site)
+## Essential links
Visit the docs site for full guides, API references and troubleshooting:
-- [Quick start](https://ryan-millard.github.io/Img2Num/info/docs/introduction/getting-started)
-- [Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/category/-guidelines)
- [Documentation](https://ryan-millard.github.io/Img2Num/info/docs/)
-- [Reference & Advanced Guides](https://ryan-millard.github.io/Img2Num/info/docs/reference/)
+- [Installation & Usage](https://ryan-millard.github.io/Img2Num/info/docs/js/)
+- [Internal Documentation](https://ryan-millard.github.io/Img2Num/info/docs/internal/)
- [Changelog](https://ryan-millard.github.io/Img2Num/info/changelog)
+- [React Example App](https://ryan-millard.github.io/Img2Num/)
## Contributing
-We welcome contributions from all places. Please read the [Contribution Guidelines](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/contributing) and the pinned issues before opening issues or pull requests.
-
-**A few important points:**
-
-- **Add tests** with your PR — new features and bug fixes **must** include tests where appropriate. PRs without tests are unlikely to be approved.
-- Follow the repository's [coding style rules](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/coding-style) and [commit message rules](https://ryan-millard.github.io/Img2Num/info/docs/guidelines/commits).
-- Use the issue and PR templates when filing issues or submitting code. Your PR will be rejected if you don't.
+See our [CONTIRBUTING.md](https://github.com/Ryan-Millard/Img2Num/blob/main/CONTRIBUTING.md)
-If you're unsure what to change, [open a discussion](https://github.com/Ryan-Millard/Img2Num/discussions/new/choose) and someone will assist you.
+## License Summary
-## License
+- **MIT** — core packages, scripts, libraries, build tools, etc.
+- **AGPLv3** — docs, example apps, CI/config.
-[AGPLv3](https://ryan-millard.github.io/Img2Num/info/docs/license)
+See the top-level [LICENSE](https://github.com/Ryan-Millard/Img2Num/blob/main/LICENSE) file for the explanation.
## Can't find something?
diff --git a/bindings/LICENSE b/bindings/LICENSE
new file mode 100644
index 000000000..6811d89ae
--- /dev/null
+++ b/bindings/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Ryan Millard
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/bindings/js/CMakeLists.txt b/bindings/js/CMakeLists.txt
new file mode 100644
index 000000000..75a1881e1
--- /dev/null
+++ b/bindings/js/CMakeLists.txt
@@ -0,0 +1,62 @@
+# =================================================================
+# JS/WASM binding using core object library
+# =================================================================
+cmake_minimum_required(VERSION 3.16)
+project(JSBindings LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+# Must be built with Emscripten
+if(NOT EMSCRIPTEN)
+ message(FATAL_ERROR "Emscripten is required to build JS bindings.")
+endif()
+
+# Collect binding sources
+file(GLOB_RECURSE BINDING_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
+file(GLOB_RECURSE BINDING_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h")
+
+# Build WASM module
+add_executable(img2num_wasm ${BINDING_SRC})
+
+# Link core library object files
+target_link_libraries(img2num_wasm PRIVATE core)
+
+# Include directories
+target_include_directories(img2num_wasm PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/include
+)
+
+# Emscripten options
+set(COMMON_FLAGS
+ "SHELL:-s MODULARIZE=1"
+ "SHELL:-s EXPORT_ES6=1"
+ "SHELL:-s ENVIRONMENT=web,worker"
+ "SHELL:-s EXPORTED_FUNCTIONS=['_malloc','_free']"
+ "SHELL:-s EXPORTED_RUNTIME_METHODS=['ccall','cwrap','getValue','setValue','HEAPU8','HEAP32','UTF8ToString','stringToUTF8','lengthBytesUTF8']"
+ "SHELL:-s INITIAL_MEMORY=128MB"
+ "SHELL:-s MAXIMUM_MEMORY=2048MB"
+ "SHELL:-s ALLOW_MEMORY_GROWTH=1"
+ "SHELL:-s EXPORT_NAME=createImg2NumModule"
+)
+
+target_compile_options(img2num_wasm PRIVATE -msimd128)
+target_link_options(img2num_wasm PRIVATE ${COMMON_FLAGS} -msimd128)
+
+# Build type flags
+if(CMAKE_BUILD_TYPE STREQUAL "Debug")
+ target_compile_options(img2num_wasm PRIVATE -O2 -g4)
+ target_link_options(img2num_wasm PRIVATE "SHELL:-s ASSERTIONS=2" -g4)
+else()
+ target_compile_options(img2num_wasm PRIVATE -O3)
+ target_link_options(img2num_wasm PRIVATE "SHELL:-s SINGLE_FILE=0")
+endif()
+
+# Output location
+set_target_properties(img2num_wasm PROPERTIES
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/packages/js/build-wasm"
+ OUTPUT_NAME "index"
+ SUFFIX ".js"
+)
+
+message(STATUS "WASM module configured: img2num_wasm")
diff --git a/bindings/js/Doxyfile b/bindings/js/Doxyfile
new file mode 100644
index 000000000..b09f0bfdd
--- /dev/null
+++ b/bindings/js/Doxyfile
@@ -0,0 +1,7 @@
+@INCLUDE = ../../docs/doxygen/Doxyfile.base
+
+PROJECT_NAME = "Img2Num JS/WASM Bindings"
+PROJECT_NUMBER = dev
+
+INPUT = src
+OUTPUT_DIRECTORY = ../../docs/static/docs/internal/bindings/js/api
diff --git a/bindings/js/src/wasm_wrapper.cpp b/bindings/js/src/wasm_wrapper.cpp
new file mode 100644
index 000000000..afbd4676d
--- /dev/null
+++ b/bindings/js/src/wasm_wrapper.cpp
@@ -0,0 +1,41 @@
+#include
+#include
+
+extern "C" {
+EMSCRIPTEN_KEEPALIVE void gaussian_blur_fft(uint8_t *image, size_t width, size_t height,
+ double sigma) {
+ img2num::gaussian_blur_fft(image, width, height, sigma);
+}
+
+EMSCRIPTEN_KEEPALIVE void invert_image(uint8_t *ptr, int width, int height) {
+ img2num::invert_image(ptr, width, height);
+}
+
+EMSCRIPTEN_KEEPALIVE void threshold_image(uint8_t *ptr, const int width, const int height,
+ const int num_thresholds) {
+ img2num::threshold_image(ptr, width, height, num_thresholds);
+}
+
+EMSCRIPTEN_KEEPALIVE void black_threshold_image(uint8_t *ptr, const int width, const int height,
+ const int num_thresholds) {
+ img2num::black_threshold_image(ptr, width, height, num_thresholds);
+}
+
+EMSCRIPTEN_KEEPALIVE void kmeans(const uint8_t *data, uint8_t *out_data, int32_t *out_labels,
+ const int32_t width, const int32_t height, const int32_t k,
+ const int32_t max_iter, const uint8_t color_space) {
+ img2num::kmeans(data, out_data, out_labels, width, height, k, max_iter, color_space);
+}
+
+EMSCRIPTEN_KEEPALIVE void bilateral_filter(uint8_t *image, size_t width, size_t height,
+ double sigma_spatial, double sigma_range,
+ uint8_t color_space) {
+ img2num::bilateral_filter(image, width, height, sigma_spatial, sigma_range, color_space);
+}
+
+EMSCRIPTEN_KEEPALIVE char *labels_to_svg(uint8_t *data, int32_t *labels, const int width,
+ const int height, const int min_area,
+ const bool draw_contour_borders) {
+ return img2num::labels_to_svg(data, labels, width, height, min_area, draw_contour_borders);
+}
+}
diff --git a/bindings/py/CMakeLists.txt b/bindings/py/CMakeLists.txt
new file mode 100644
index 000000000..39e949139
--- /dev/null
+++ b/bindings/py/CMakeLists.txt
@@ -0,0 +1,13 @@
+# =================================================================
+# Python bindings via pybind11
+# =================================================================
+find_package(Python COMPONENTS Interpreter Development REQUIRED)
+find_package(pybind11 REQUIRED)
+
+pybind11_add_module(img2num_python
+ src/python_wrapper.cpp
+)
+
+# Link Python module to shared core library
+target_link_libraries(img2num_python PRIVATE img2num_core)
+target_include_directories(img2num_python PRIVATE ${CMAKE_SOURCE_DIR}/core/include)
diff --git a/bindings/py/src/python_wrapper.cpp b/bindings/py/src/python_wrapper.cpp
new file mode 100644
index 000000000..478918b10
--- /dev/null
+++ b/bindings/py/src/python_wrapper.cpp
@@ -0,0 +1,11 @@
+#include
+
+#include "img2num.h"
+
+namespace py = pybind11;
+
+PYBIND11_MODULE(img2num, m) {
+ m.doc() = "Img2Num library";
+
+ // m.def("some_function", &some_function, "A function from Img2Num");
+}
diff --git a/src/wasm/.gitignore b/core/.gitignore
similarity index 90%
rename from src/wasm/.gitignore
rename to core/.gitignore
index f5539311f..ad9e46aa9 100644
--- a/src/wasm/.gitignore
+++ b/core/.gitignore
@@ -1,5 +1,5 @@
-# WASM build directory
build/
+cmake-build/
# C++ object and binary files
*.o
diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt
new file mode 100644
index 000000000..7abebbd8e
--- /dev/null
+++ b/core/CMakeLists.txt
@@ -0,0 +1,31 @@
+# =================================================================
+# Img2Num Core (Object Library)
+# =================================================================
+cmake_minimum_required(VERSION 3.16)
+project(CoreLibrary LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+file(GLOB_RECURSE CORE_SRC
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp"
+)
+
+add_library(core OBJECT ${CORE_SRC})
+
+# PUBLIC: only expose the directory that contains img2num.h
+# PRIVATE: internal headers
+target_include_directories(core
+ PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR} # img2num.h
+ PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}/include # internal headers
+)
+
+# Emscripten flags
+if(EMSCRIPTEN)
+ target_compile_options(core PRIVATE -msimd128)
+ target_link_options(core PRIVATE -msimd128)
+endif()
+
+message(STATUS "Core library configured with ${CORE_SRC}")
diff --git a/core/Doxyfile b/core/Doxyfile
new file mode 100644
index 000000000..d9fd3ab63
--- /dev/null
+++ b/core/Doxyfile
@@ -0,0 +1,7 @@
+@INCLUDE = ../docs/doxygen/Doxyfile.base
+
+PROJECT_NAME = "Img2Num Core"
+PROJECT_NUMBER = dev
+
+INPUT = img2num.h include src
+OUTPUT_DIRECTORY = ../docs/static/docs/internal/core/api
diff --git a/core/LICENSE b/core/LICENSE
new file mode 100644
index 000000000..6811d89ae
--- /dev/null
+++ b/core/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Ryan Millard
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/core/img2num.h b/core/img2num.h
new file mode 100644
index 000000000..d6c52c79c
--- /dev/null
+++ b/core/img2num.h
@@ -0,0 +1,93 @@
+/** @file img2num.h
+ * @brief Core image processing functions for img2num project.
+ * @details This file declares functions for image manipulation, clustering, filtering,
+ * and conversion to SVG. Functions operate on raw image buffers (uint8_t*).
+ * @defgroup IMG2NUM_H Img2Num Core Functions
+ */
+#ifndef IMG2NUM_H
+#define IMG2NUM_H
+
+#include
+#include
+
+/// @note All image buffers are assumed to be stored in row-major order, unless otherwise noted.
+namespace img2num {
+
+/// @brief Apply a Gaussian blur to an image using FFT.
+/// @ingroup IMG2NUM_H
+/// @param image Pointer to the image buffer (grayscale or single-channel).
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @param sigma Standard deviation for Gaussian kernel.
+/// @note The operation modifies the image buffer in-place.
+void gaussian_blur_fft(uint8_t *image, size_t width, size_t height, double sigma);
+
+/// @brief Invert the pixel values of an image.
+/// @ingroup IMG2NUM_H
+/// @param ptr Pointer to the image buffer.
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @note Each pixel value is replaced by 255 - original_value.
+void invert_image(uint8_t *ptr, int width, int height);
+
+/// @brief Apply a thresholding operation to an image.
+/// @ingroup IMG2NUM_H
+/// @param ptr Pointer to the image buffer.
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @param num_thresholds Number of thresholds to apply.
+/// @note Thresholds split pixel intensity ranges into discrete levels.
+void threshold_image(uint8_t *ptr, const int width, const int height, const int num_thresholds);
+
+/// @brief Apply black-thresholding to an image.
+/// @ingroup IMG2NUM_H
+/// @param ptr Pointer to the image buffer.
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @param num_thresholds Number of thresholds to apply.
+/// @note Similar to threshold_image but prioritizes darker pixels.
+void black_threshold_image(uint8_t *ptr, const int width, const int height,
+ const int num_thresholds);
+
+/// @brief Perform k-means clustering on image data.
+/// @ingroup IMG2NUM_H
+/// @param data Pointer to input image data buffer.
+/// @param out_data Pointer to output buffer where clustered pixel values are stored.
+/// @param out_labels Pointer to output buffer for cluster labels per pixel.
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @param k Number of clusters to compute.
+/// @param max_iter Maximum number of iterations for the algorithm.
+/// @param color_space Color space flag (0 = grayscale, 1 = RGB, etc.).
+/// @note The function does not modify the input buffer.
+void kmeans(const uint8_t *data, uint8_t *out_data, int32_t *out_labels, const int32_t width,
+ const int32_t height, const int32_t k, const int32_t max_iter,
+ const uint8_t color_space);
+
+/// @brief Apply bilateral filtering to an image.
+/// @ingroup IMG2NUM_H
+/// @param image Pointer to RGBA pixel buffer.
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @param sigma_spatial Standard deviation for spatial Gaussian (proximity weight).
+/// @param sigma_range Standard deviation for range Gaussian (intensity similarity weight).
+/// @param color_space Color space flag (0 = grayscale, 1 = RGB, etc.).
+/// @note The filter modifies the image buffer in-place.
+void bilateral_filter(uint8_t *image, size_t width, size_t height, double sigma_spatial,
+ double sigma_range, uint8_t color_space);
+
+/// @brief Convert labeled regions of an image into an SVG string.
+/// @ingroup IMG2NUM_H
+/// @param data Pointer to image data buffer.
+/// @param labels Pointer to label buffer, indicating region for each pixel.
+/// @param width Width of the image in pixels.
+/// @param height Height of the image in pixels.
+/// @param min_area Minimum area (in pixels) for a region to be included in the SVG.
+/// @param draw_contour_borders If true, contours of labeled regions will be drawn.
+/// @return Pointer to a dynamically allocated C-string containing the SVG data.
+/// @note Caller is responsible for freeing the returned string.
+char *labels_to_svg(uint8_t *data, int32_t *labels, const int width, const int height,
+ const int min_area, const bool draw_contour_borders);
+} // namespace img2num
+
+#endif // IMG2NUM_H
diff --git a/core/include/Image.h b/core/include/Image.h
new file mode 100644
index 000000000..b7ceddad8
--- /dev/null
+++ b/core/include/Image.h
@@ -0,0 +1,116 @@
+#ifndef IMAGE_H
+#define IMAGE_H
+
+#include
+#include
+#include
+#include
+
+#include "Pixel.h"
+#include "PixelConverter.h"
+
+namespace ImageLib {
+template
+class Image {
+ static_assert(std::is_base_of_v, PixelT>,
+ "Image: PixelT must derive from Pixel");
+
+ public:
+ Image() : width(0), height(0) {
+ }
+ Image(int width, int height, PixelT fill = PixelT())
+ : width(width), height(height), data(width * height, fill) {
+ }
+
+ template
+ void loadFromBuffer(const uint8_t *buffer, int width, int height,
+ PixelConverter converter) {
+ // converter.convert must return exactly PixelT
+ static_assert(std::is_same_v,
+ "Converter return type must match PixelT");
+
+ this->width = width;
+ this->height = height;
+ const int pixelCount = getPixelCount();
+ data.resize(pixelCount);
+ for (int i = 0; i < pixelCount; ++i) {
+ data[i] = converter.convert(&buffer[i * converter.bytesPerPixel]);
+ }
+ }
+
+ void fill(const PixelT &color) {
+ std::fill(data.begin(), data.end(), color);
+ }
+
+ using iter = typename std::vector::iterator;
+ iter begin() {
+ return data.begin();
+ }
+ iter end() {
+ return data.end();
+ }
+ using const_iter = typename std::vector::const_iterator;
+ const_iter begin() const {
+ return data.begin();
+ }
+ const_iter end() const {
+ return data.end();
+ }
+
+ int getWidth() const {
+ return width;
+ }
+ int getHeight() const {
+ return height;
+ }
+ int getPixelCount() const {
+ return width * height;
+ }
+ int getSize() const {
+ return getPixelCount();
+ }
+
+ const std::vector &getData() const {
+ return data;
+ }
+
+ const PixelT &getPixel(int x, int y) const {
+ return data[index(x, y)];
+ }
+ PixelT &getPixel(int x, int y) {
+ return data[index(x, y)];
+ }
+
+ void setPixel(int x, int y, const PixelT &p) {
+ data[index(x, y)] = p;
+ }
+
+ // Operator[] for flat indexing
+ PixelT &operator[](int idx) {
+ return data.at(idx);
+ } // set
+ const PixelT &operator[](int idx) const {
+ return data.at(idx);
+ } // get
+
+ // Operator() for (x, y) access
+ PixelT &operator()(int x, int y) {
+ return data.at(index(x, y));
+ } // set
+ const PixelT &operator()(int x, int y) const {
+ return data.at(index(x, y));
+ } // get
+
+ private:
+ std::vector data;
+ int width, height;
+
+ int index(int x, int y) const {
+ if (x < 0 || y < 0 || x >= width || y >= height)
+ throw std::out_of_range("Pixel coordinates out of bounds");
+ return y * width + x;
+ }
+};
+} // namespace ImageLib
+
+#endif
diff --git a/core/include/LABAPixel.h b/core/include/LABAPixel.h
new file mode 100644
index 000000000..24bf46788
--- /dev/null
+++ b/core/include/LABAPixel.h
@@ -0,0 +1,34 @@
+#ifndef LABAPixel_H
+#define LABAPixel_H
+
+#include "LABPixel.h"
+
+namespace ImageLib {
+template
+struct LABAPixel : public ImageLib::LABPixel {
+ // ----- Members -----
+ NumberT alpha;
+
+ // ----- Constructors -----
+ constexpr LABAPixel(NumberT l = 0, NumberT a = 0, NumberT b = 0, NumberT alpha = 255)
+ : LABPixel(l, a, b), alpha(alpha) {
+ }
+
+ // ----- Modifiers -----
+ [[nodiscard]] inline bool operator==(const LABAPixel &other) const {
+ return LABPixel::operator==(other) && alpha == other.alpha;
+ }
+ [[nodiscard]] inline bool operator!=(const LABAPixel &other) const {
+ return !(*this == other);
+ }
+
+ // ----- Utilities -----
+ inline void setGray(NumberT gray, NumberT alpha = 255) {
+ LABPixel::setGray(gray);
+ this->alpha = alpha;
+ }
+
+} __attribute__((packed));
+} // namespace ImageLib
+
+#endif // LABAPixel_H
diff --git a/core/include/LABPixel.h b/core/include/LABPixel.h
new file mode 100644
index 000000000..85d5b0946
--- /dev/null
+++ b/core/include/LABPixel.h
@@ -0,0 +1,48 @@
+#ifndef LABPIXEL_H
+#define LABPIXEL_H
+
+#include
+
+#include "Pixel.h"
+
+/*
+can support signed data types
+preferrably float or double
+*/
+
+namespace ImageLib {
+template
+struct LABPixel : public Pixel {
+ // ----- Members -----
+ NumberT l, a, b;
+
+ constexpr LABPixel(NumberT l = 0, NumberT a = 0, NumberT b = 0) : l(l), a(a), b(b) {
+ }
+
+ // ----- Modifiers -----
+ [[nodiscard]] inline bool operator==(const LABPixel &other) const {
+ return l == other.l && a == other.a && b == other.b;
+ }
+ [[nodiscard]] inline bool operator!=(const LABPixel &other) const {
+ return !(*this == other);
+ }
+
+ // ----- Utilities -----
+ inline void setGray(NumberT new_luma) {
+ l = new_luma;
+ a = b = 0;
+ }
+
+ static inline float colorDistance(const LABPixel &a, const LABPixel &b) {
+ LABPixel af{static_cast(a.l), static_cast(a.a),
+ static_cast(a.b)};
+ LABPixel bf{static_cast(b.l), static_cast(b.a),
+ static_cast(b.b)};
+ return std::sqrt((a.l - b.l) * (a.l - b.l) + (a.a - b.a) * (a.a - b.a) +
+ (a.b - b.b) * (a.b - b.b));
+ }
+
+} __attribute__((packed));
+} // namespace ImageLib
+
+#endif // LABPIXEL_H
diff --git a/core/include/Pixel.h b/core/include/Pixel.h
new file mode 100644
index 000000000..01aea89e0
--- /dev/null
+++ b/core/include/Pixel.h
@@ -0,0 +1,18 @@
+#ifndef PIXEL_H
+#define PIXEL_H
+
+#include
+
+namespace ImageLib {
+template
+struct Pixel {
+ static_assert(std::is_arithmetic::value,
+ "Pixel: NumberT must be a numeric type");
+
+ using value_type = NumberT;
+
+ ~Pixel() = default;
+};
+} // namespace ImageLib
+
+#endif // PIXEL_H
diff --git a/core/include/PixelConverter.h b/core/include/PixelConverter.h
new file mode 100644
index 000000000..b7063c280
--- /dev/null
+++ b/core/include/PixelConverter.h
@@ -0,0 +1,20 @@
+#ifndef PIXELCONVERTER_H
+#define PIXELCONVERTER_H
+
+#include
+#include // for std::move
+
+namespace ImageLib {
+template
+
+struct PixelConverter {
+ ConverterT convert;
+ uint8_t bytesPerPixel;
+
+ PixelConverter(ConverterT conv, uint8_t bpp) : convert(std::move(conv)), bytesPerPixel(bpp) {
+ }
+};
+
+} // namespace ImageLib
+
+#endif
diff --git a/src/wasm/modules/image/include/PixelConverters.h b/core/include/PixelConverters.h
similarity index 53%
rename from src/wasm/modules/image/include/PixelConverters.h
rename to core/include/PixelConverters.h
index 74fb382f4..919c4e369 100644
--- a/src/wasm/modules/image/include/PixelConverters.h
+++ b/core/include/PixelConverters.h
@@ -9,25 +9,23 @@
namespace ImageLib {
template
inline RGBPixel convertRGB(const uint8_t *p) {
- return RGBPixel{static_cast(p[0]),
- static_cast(p[1]),
- static_cast(p[2])};
+ return RGBPixel{static_cast(p[0]), static_cast(p[1]),
+ static_cast(p[2])};
}
template
inline RGBAPixel convertRGBA(const uint8_t *p) {
- return RGBAPixel{
- static_cast(p[0]), static_cast(p[1]),
- static_cast(p[2]), static_cast(p[3])};
+ return RGBAPixel{static_cast(p[0]), static_cast(p[1]),
+ static_cast(p[2]), static_cast(p[3])};
}
template
-inline const PixelConverter (*)(const uint8_t *)>
- RGB_CONVERTER{convertRGB, 3}; // 3 bytes per pixel
+inline const PixelConverter (*)(const uint8_t *)> RGB_CONVERTER{
+ convertRGB, 3}; // 3 bytes per pixel
template
-inline const PixelConverter (*)(const uint8_t *)>
- RGBA_CONVERTER{convertRGBA, 4}; // 4 bytes per pixel
+inline const PixelConverter (*)(const uint8_t *)> RGBA_CONVERTER{
+ convertRGBA, 4}; // 4 bytes per pixel
-} // namespace ImageLib
+} // namespace ImageLib
#endif
diff --git a/core/include/Point.h b/core/include/Point.h
new file mode 100644
index 000000000..f4b65a517
--- /dev/null
+++ b/core/include/Point.h
@@ -0,0 +1,45 @@
+#ifndef POINT_H
+#define POINT_H
+
+// will start as integer values but can be adjusted to subpixel positions
+struct Point {
+ float x = 0;
+ float y = 0;
+
+ Point operator+(const Point &other) const {
+ return Point{x + other.x, y + other.y};
+ }
+
+ // Overload the - operator (subtraction)
+ Point operator-(const Point &other) const {
+ return Point{x - other.x, y - other.y};
+ }
+
+ // Overload the * operator (multiplication by a scalar)
+ // The left operand is the class object (this), the right is a double.
+ Point operator*(float scalar) const {
+ return Point{x * scalar, y * scalar};
+ }
+
+ Point operator/(float scalar) const {
+ return Point{x / scalar, y / scalar};
+ }
+
+ // Friend function to allow float * Vector
+ friend Point operator*(float scalar, const Point &v) {
+ return Point{v.x * scalar, v.y * scalar};
+ ; // Calls the member function for the actual logic
+ }
+
+ Point &operator+=(const Point &other) {
+ x += other.x;
+ y += other.y;
+ return *this;
+ }
+
+ static float distSq(Point a, Point b) {
+ return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
+ }
+};
+
+#endif
\ No newline at end of file
diff --git a/core/include/RGBAPixel.h b/core/include/RGBAPixel.h
new file mode 100644
index 000000000..fdd88496b
--- /dev/null
+++ b/core/include/RGBAPixel.h
@@ -0,0 +1,34 @@
+#ifndef RGBAPIXEL_H
+#define RGBAPIXEL_H
+
+#include "RGBPixel.h"
+
+namespace ImageLib {
+template
+struct RGBAPixel : public ImageLib::RGBPixel {
+ // ----- Members -----
+ NumberT alpha;
+
+ // ----- Constructors -----
+ constexpr RGBAPixel(NumberT red = 0, NumberT green = 0, NumberT blue = 0, NumberT alpha = 255)
+ : RGBPixel(red, green, blue), alpha(alpha) {
+ }
+
+ // ----- Modifiers -----
+ [[nodiscard]] inline bool operator==(const RGBAPixel &other) const {
+ return RGBPixel::operator==(other) && alpha == other.alpha;
+ }
+ [[nodiscard]] inline bool operator!=(const RGBAPixel &other) const {
+ return !(*this == other);
+ }
+
+ // ----- Utilities -----
+ inline void setGray(NumberT gray, NumberT alpha = 255) {
+ RGBPixel::setGray(gray);
+ this->alpha = alpha;
+ }
+
+} __attribute__((packed));
+} // namespace ImageLib
+
+#endif // RGBAPIXEL_H
diff --git a/core/include/RGBPixel.h b/core/include/RGBPixel.h
new file mode 100644
index 000000000..9d540faa5
--- /dev/null
+++ b/core/include/RGBPixel.h
@@ -0,0 +1,44 @@
+#ifndef RGBPIXEL_H
+#define RGBPIXEL_H
+
+#include
+
+#include "Pixel.h"
+
+namespace ImageLib {
+template
+struct RGBPixel : public Pixel {
+ // ----- Members -----
+ NumberT red, green, blue;
+
+ constexpr RGBPixel(NumberT red = 0, NumberT green = 0, NumberT blue = 0)
+ : red(red), green(green), blue(blue) {
+ }
+
+ // ----- Modifiers -----
+ [[nodiscard]] inline bool operator==(const RGBPixel &other) const {
+ return red == other.red && green == other.green && blue == other.blue;
+ }
+ [[nodiscard]] inline bool operator!=(const RGBPixel &other) const {
+ return !(*this == other);
+ }
+
+ // ----- Utilities -----
+ inline void setGray(NumberT gray) {
+ red = green = blue = gray;
+ }
+
+ static inline float colorDistance(const RGBPixel &a, const RGBPixel &b) {
+ RGBPixel af{static_cast(a.red), static_cast(a.green),
+ static_cast(a.blue)};
+ RGBPixel bf{static_cast(b.red), static_cast(b.green),
+ static_cast(b.blue)};
+ return std::sqrt((af.red - bf.red) * (af.red - bf.red) +
+ (af.green - bf.green) * (af.green - bf.green) +
+ (af.blue - bf.blue) * (af.blue - bf.blue));
+ }
+
+} __attribute__((packed));
+} // namespace ImageLib
+
+#endif // RGBPIXEL_H
diff --git a/core/include/SavitskyGolay.h b/core/include/SavitskyGolay.h
new file mode 100644
index 000000000..5c15d2451
--- /dev/null
+++ b/core/include/SavitskyGolay.h
@@ -0,0 +1,29 @@
+#ifndef SAVITZKYGOLAY_H
+#define SAVITZKYGOLAY_H
+
+#include
+
+#include "Point.h"
+
+struct Point;
+
+class SavitzkyGolay {
+ private:
+ int window_size_;
+ int window_radius_; // half window size
+ int poly_order_;
+ std::vector coeffs_;
+
+ std::vector> invert_matrix(std::vector> A);
+ void compute_coefficients();
+
+ public:
+ SavitzkyGolay(int radius, int poly_order);
+ std::vector filter(const std::vector &data);
+ std::vector filter_wrap(const std::vector &data);
+ std::vector get_coeffs() const {
+ return coeffs_;
+ }
+};
+
+#endif // SAVITZKYGOLAY_H
diff --git a/src/wasm/modules/image/include/bezier.h b/core/include/bezier.h
similarity index 79%
rename from src/wasm/modules/image/include/bezier.h
rename to core/include/bezier.h
index b35937143..6ec4ab626 100644
--- a/src/wasm/modules/image/include/bezier.h
+++ b/core/include/bezier.h
@@ -4,6 +4,5 @@
#include "contours.h"
void fit_curve_reduction(const std::vector> &chains,
- std::vector> &results,
- float tolerance);
+ std::vector> &results, float tolerance);
#endif
\ No newline at end of file
diff --git a/src/wasm/modules/image/include/cielab.h b/core/include/cielab.h
similarity index 53%
rename from src/wasm/modules/image/include/cielab.h
rename to core/include/cielab.h
index 72e339140..bf60cbca3 100644
--- a/src/wasm/modules/image/include/cielab.h
+++ b/core/include/cielab.h
@@ -1,39 +1,35 @@
#ifndef CIELAB_H
#define CIELAB_H
+#include
+#include
+
#include "LABAPixel.h"
#include "LABPixel.h"
#include "RGBAPixel.h"
#include "RGBPixel.h"
-#include
-#include
// templates must be in headers
template
-void rgb_to_lab(const Tin r_u8, const Tin g_u8, const Tin b_u8, Tout &out_l,
- Tout &out_a, Tout &out_b);
+void rgb_to_lab(const Tin r_u8, const Tin g_u8, const Tin b_u8, Tout &out_l, Tout &out_a,
+ Tout &out_b);
template
-void lab_to_rgb(const Tin L, const Tin A, const Tin B, Tout &r_u8, Tout &g_u8,
- Tout &b_u8);
+void lab_to_rgb(const Tin L, const Tin A, const Tin B, Tout &r_u8, Tout &g_u8, Tout &b_u8);
template
-void rgb_to_lab(const ImageLib::RGBAPixel &rgba,
- ImageLib::LABAPixel &laba);
+void rgb_to_lab(const ImageLib::RGBAPixel &rgba, ImageLib::LABAPixel &laba);
template
-void rgb_to_lab(const ImageLib::RGBPixel &rgb,
- ImageLib::LABPixel &lab);
+void rgb_to_lab(const ImageLib::RGBPixel &rgb, ImageLib::LABPixel &lab);
template
-void lab_to_rgb(const ImageLib::LABAPixel &laba,
- ImageLib::RGBAPixel &rgba);
+void lab_to_rgb(const ImageLib::LABAPixel &laba, ImageLib::RGBAPixel &rgba);
template
-void lab_to_rgb(const ImageLib::LABPixel &lab,
- ImageLib::RGBPixel &rgb);
+void lab_to_rgb(const ImageLib::LABPixel &lab, ImageLib::RGBPixel &rgb);
#include "cielab_impl.h"
-#endif // CIELAB_H
+#endif // CIELAB_H
diff --git a/core/include/cielab_impl.h b/core/include/cielab_impl.h
new file mode 100644
index 000000000..a1788bd83
--- /dev/null
+++ b/core/include/cielab_impl.h
@@ -0,0 +1,216 @@
+#ifndef CIELAB_IMPL_H
+#define CIELAB_IMPL_H
+
+#ifndef CIELAB_H
+#error "cielab_impl.h should not be included directly; include cielab.h instead"
+#endif
+
+#include
+#include
+
+// ====== Used in xyz_to_lab =======
+constexpr double DELTA{6.0 / 29.0}; // 0.2068966
+constexpr double DELTA_CUBED{DELTA * DELTA * DELTA}; // 0.008856
+constexpr double KAPPA{1.0 / (3.0 * DELTA * DELTA)}; // 7.787
+constexpr double EPSILON{16.0 / 116.0}; // 0.137931
+
+// ====== Used in srgb_to_linear ======
+constexpr double SRGB_LINEAR_THRESHOLD{0.04045}; // linear segment boundary
+constexpr double SRGB_LINEAR_FACTOR{12.92}; // scale factor for linear segment
+constexpr double SRGB_GAMMA_OFFSET{0.055}; // offset for nonlinear segment
+constexpr double SRGB_GAMMA{2.4}; // gamma exponent for nonlinear segment
+constexpr double SRGB_GAMMA_INV{1.0 / SRGB_GAMMA}; // gamma exponent for nonlinear segment
+
+/*
+ * ====== Used in rgb_to_lab ======
+ *
+ * sRGB Khronos/W3C Transformation Matrices (D65 illuminant)
+ *
+ * sRGB → CIE XYZ:
+ * ┌ ┐ ┌ ┐ ┌ ┐
+ * │ X │ │ 0.4124564 0.3575761 0.1804375 │ │ R │
+ * │ Y │ = │ 0.2126729 0.7151522 0.0721750 │ │ G │
+ * │ Z │ │ 0.0193339 0.1191920 0.9503041 │ │ B │
+ * └ ┘ └ ┘ └ ┘
+ *
+ * Reference: ITU-R BT.709 / sRGB standard (IEC 61966-2-1:1999)
+ */
+constexpr double SRGB_R_TO_X{0.4124564};
+constexpr double SRGB_G_TO_X{0.3575761};
+constexpr double SRGB_B_TO_X{0.1804375};
+constexpr double SRGB_R_TO_Y{0.2126729};
+constexpr double SRGB_G_TO_Y{0.7151522};
+constexpr double SRGB_B_TO_Y{0.0721750};
+constexpr double SRGB_R_TO_Z{0.0193339};
+constexpr double SRGB_G_TO_Z{0.1191920};
+constexpr double SRGB_B_TO_Z{0.9503041};
+
+/*
+ * ====== Used in lab_to_rgb ======
+ *
+ * sRGB Khronos/W3C Transformation Matrices (D65 illuminant)
+ * Inverse transformation (XYZ → sRGB) per Khronos/W3C, D65 white, slightly
+ * different from original BT.709 inverse.
+ *
+ * CIE XYZ → sRGB (inverse):
+ * ┌ ┐ ┌ ┐ ┌ ┐
+ * │ R │ │ 3.240970 -1.537383 -0.498611 │ │ X │
+ * │ G │ = │ -0.969244 1.875968 0.041555 │ │ Y │
+ * │ B │ │ 0.055630 -0.203977 1.056972 │ │ Z │
+ * └ ┘ └ ┘ └ ┘
+ *
+ * Reference: ITU-R BT.709 / sRGB standard (IEC 61966-2-1:1999)
+ */
+constexpr double SRGB_X_TO_R{3.240970};
+constexpr double SRGB_Y_TO_R{-1.537383};
+constexpr double SRGB_Z_TO_R{-0.498611};
+constexpr double SRGB_X_TO_G{-0.969244};
+constexpr double SRGB_Y_TO_G{1.875968};
+constexpr double SRGB_Z_TO_G{0.041555};
+constexpr double SRGB_X_TO_B{0.055630};
+constexpr double SRGB_Y_TO_B{-0.203977};
+constexpr double SRGB_Z_TO_B{1.056972};
+
+// Reference white point for D65 illuminant
+constexpr double D65_Xn{0.95047};
+constexpr double D65_Yn{1.0};
+constexpr double D65_Zn{1.08883};
+
+constexpr double LAB_L_FACTOR{116.0};
+constexpr double LAB_L_OFFSET{16.0};
+constexpr double LAB_A_FACTOR{500.0};
+constexpr double LAB_B_FACTOR{200.0};
+
+// Function for the non-linear XYZ to Lab transformation
+inline double xyz_to_lab(const double t) {
+ // prevent negative due to tiny floating errors
+ const double safe_t{std::max(0.0, t)};
+ return (safe_t > DELTA_CUBED) ? std::cbrt(safe_t) : (KAPPA * safe_t) + EPSILON;
+}
+
+// Function for the non-linear sRGB to linear RGB transformation (inverse gamma
+// correction)
+inline double srgb_to_linear(const double c) {
+ const double safe_c{std::clamp(c, 0.0, 1.0)};
+ return (safe_c <= SRGB_LINEAR_THRESHOLD)
+ ? safe_c / SRGB_LINEAR_FACTOR
+ : std::pow((safe_c + SRGB_GAMMA_OFFSET) / (1.0 + SRGB_GAMMA_OFFSET), SRGB_GAMMA);
+}
+
+template
+void rgb_to_lab(const Tin r_u8, const Tin g_u8, const Tin b_u8, Tout &out_l, Tout &out_a,
+ Tout &out_b) {
+ // 1. Convert 8-bit RGB [0, 255] to linear RGB [0.0, 1.0]
+
+ double _r = static_cast(r_u8);
+ double _g = static_cast(g_u8);
+ double _b = static_cast(b_u8);
+
+ double r{srgb_to_linear(_r / 255.0)};
+ double g{srgb_to_linear(_g / 255.0)};
+ double b{srgb_to_linear(_b / 255.0)};
+
+ // 2. Convert linear RGB to CIE XYZ (using D65 white point reference)
+ // The matrix below is for sRGB to XYZ (D65)
+ const double x{SRGB_R_TO_X * r + SRGB_G_TO_X * g + SRGB_B_TO_X * b};
+ const double y{SRGB_R_TO_Y * r + SRGB_G_TO_Y * g + SRGB_B_TO_Y * b};
+ const double z{SRGB_R_TO_Z * r + SRGB_G_TO_Z * g + SRGB_B_TO_Z * b};
+
+ // Normalize XYZ values by the white point
+ const double Xr{x / D65_Xn};
+ const double Yr{y / D65_Yn};
+ const double Zr{z / D65_Zn};
+
+ // 3. Convert CIE XYZ to CIE L*a*b*
+ const double fx{xyz_to_lab(Xr)};
+ const double fy{xyz_to_lab(Yr)};
+ const double fz{xyz_to_lab(Zr)};
+
+ // 4. Output values
+ out_l = static_cast(LAB_L_FACTOR * fy - LAB_L_OFFSET);
+ out_a = static_cast(LAB_A_FACTOR * (fx - fy));
+ out_b = static_cast(LAB_B_FACTOR * (fy - fz));
+
+ out_l = std::clamp(out_l, static_cast(0.0), static_cast(100.0));
+}
+
+constexpr double inverse_xyz_to_lab(double t) {
+ return (t > DELTA) ? (t * t * t) : (3 * DELTA * DELTA * (t - EPSILON));
+}
+
+inline double gamma_encode(double u) {
+ // Guard against negative values from out-of-gamut colors
+ u = std::max(0.0, u);
+ return (u <= SRGB_LINEAR_THRESHOLD / SRGB_LINEAR_FACTOR)
+ ? SRGB_LINEAR_FACTOR * u
+ : (1.0 + SRGB_GAMMA_OFFSET) * std::pow(u, SRGB_GAMMA_INV) - SRGB_GAMMA_OFFSET;
+}
+
+template
+void lab_to_rgb(const Tin L, const Tin A, const Tin B, Tout &out_r_u8, Tout &out_g_u8,
+ Tout &out_b_u8) {
+ const double _L = static_cast(L);
+ const double _A = static_cast(A);
+ const double _B = static_cast(B);
+
+ // --- Lab → XYZ (D65 white point)
+ const double fy{(_L + LAB_L_OFFSET) / LAB_L_FACTOR};
+ const double fx{fy + _A / LAB_A_FACTOR};
+ const double fz{fy - _B / LAB_B_FACTOR};
+
+ const double X{D65_Xn * inverse_xyz_to_lab(fx)};
+ const double Y{D65_Yn * inverse_xyz_to_lab(fy)};
+ const double Z{D65_Zn * inverse_xyz_to_lab(fz)};
+
+ // --- XYZ → linear RGB (sRGB)
+ double r{SRGB_X_TO_R * X + SRGB_Y_TO_R * Y + SRGB_Z_TO_R * Z};
+ double g{SRGB_X_TO_G * X + SRGB_Y_TO_G * Y + SRGB_Z_TO_G * Z};
+ double b{SRGB_X_TO_B * X + SRGB_Y_TO_B * Y + SRGB_Z_TO_B * Z};
+
+ // --- linear RGB → sRGB (gamma correction)
+ r = gamma_encode(std::clamp(r, 0.0, 1.0));
+ g = gamma_encode(std::clamp(g, 0.0, 1.0));
+ b = gamma_encode(std::clamp(b, 0.0, 1.0));
+
+ // --- Clamp and convert to 8-bit
+ out_r_u8 = static_cast(std::round(255.0 * std::clamp(r, 0.0, 1.0)));
+ out_g_u8 = static_cast(std::round(255.0 * std::clamp(g, 0.0, 1.0)));
+ out_b_u8 = static_cast(std::round(255.0 * std::clamp(b, 0.0, 1.0)));
+}
+
+template
+void rgb_to_lab(const ImageLib::RGBAPixel &rgba, ImageLib::LABAPixel &laba) {
+ Tout l{laba.l};
+ Tout a{laba.a};
+ Tout b{laba.b};
+
+ rgb_to_lab(rgba.red, rgba.green, rgba.blue, l, a, b);
+
+ laba.l = l;
+ laba.a = a;
+ laba.b = b;
+
+ laba.alpha = static_cast(rgba.alpha);
+}
+
+template
+void rgb_to_lab(const ImageLib::RGBPixel &rgb, ImageLib::LABPixel &lab) {
+ rgb_to_lab(rgb.red, rgb.green, rgb.blue, lab.l, lab.a, lab.b);
+}
+
+template
+void lab_to_rgb(const ImageLib::LABAPixel &laba, ImageLib::RGBAPixel &rgba) {
+ Tout r{rgba.red};
+ Tout g{rgba.green};
+ Tout b{rgba.blue};
+
+ lab_to_rgb(laba.l, laba.a, laba.b, r, g, b);
+ rgba.alpha = static_cast(laba.alpha);
+}
+
+template
+void lab_to_rgb(const ImageLib::LABPixel &lab, ImageLib::RGBPixel &rgb) {
+ lab_to_rgb(lab.l, lab.a, lab.b, rgb.red, rgb.green, rgb.blue);
+}
+
+#endif
diff --git a/core/include/contours.h b/core/include/contours.h
new file mode 100644
index 000000000..4d50afdb6
--- /dev/null
+++ b/core/include/contours.h
@@ -0,0 +1,57 @@
+#ifndef CONTOURS_H
+#define CONTOURS_H
+
+#include
+#include
+#include
+#include
+#include
+
+#include "Image.h"
+#include "PixelConverters.h"
+#include "Point.h"
+#include "RGBAPixel.h"
+#include "SavitskyGolay.h"
+
+struct QuadBezier {
+ Point p0{0, 0}; // Start
+ Point p1{0, 0}; // Control
+ Point p2{0, 0}; // End
+};
+
+struct Rect {
+ float x, y, width, height;
+};
+
+struct ContoursResult {
+ // contours[k] is a sequence of boundary pixels (x,y) in image coordinates
+ // (0..w-1, 0..h-1)
+ std::vector> contours;
+ std::vector> curves;
+
+ // hierarchy[k] = { next_sibling, prev_sibling, first_child, parent }
+ // -1 means "none"
+ std::vector> hierarchy;
+
+ // is_hole[k] == true if contour k is a hole border
+ std::vector is_hole;
+};
+
+struct ColoredContours : ContoursResult {
+ // inherits: contours, hierarchy, is_hole
+
+ std::vector> colors;
+};
+
+namespace contours {
+ContoursResult find_contours(const std::vector &binary, int width, int height);
+
+void stitch_smooth(std::vector &vecA, std::vector &vecB);
+void coupled_smooth(std::vector> &contours, Rect bounds);
+
+void pack_with_boundary_constraints(std::vector> &contours, Rect bounds,
+ int iterations = 15);
+
+} // namespace contours
+
+#endif
\ No newline at end of file
diff --git a/src/wasm/modules/image/include/fft_iterative.h b/core/include/fft_iterative.h
similarity index 87%
rename from src/wasm/modules/image/include/fft_iterative.h
rename to core/include/fft_iterative.h
index 0655505a1..52057d67c 100644
--- a/src/wasm/modules/image/include/fft_iterative.h
+++ b/core/include/fft_iterative.h
@@ -2,7 +2,7 @@
#define ITERATIVE_FFT_H
#include
-#include // for size_t
+#include // for size_t
#include
namespace fft {
@@ -35,16 +35,14 @@ std::vector fft_copy(const std::vector &input, bool inverse = false);
// Parameters:
// - data: input/output buffer (modified in-place).
// - inverse: false for forward FFT, true for inverse FFT.
-void iterative_fft_2d(std::vector &a, size_t width, size_t height,
- bool inverse = false);
+void iterative_fft_2d(std::vector &a, size_t width, size_t height, bool inverse = false);
// Convenience wrapper: return 2D FFT result as a new vector.
// Parameters:
// - input: const input vector.
// - inverse: false for forward FFT, true for inverse FFT.
-std::vector iterative_fft_2d_copy(const std::vector &input,
- size_t width, size_t height,
+std::vector iterative_fft_2d_copy(const std::vector &input, size_t width, size_t height,
bool inverse = false);
-} // namespace fft
+} // namespace fft
-#endif // ITERATIVE_FFT_H
+#endif // ITERATIVE_FFT_H
diff --git a/src/wasm/modules/image/include/graph.h b/core/include/graph.h
similarity index 50%
rename from src/wasm/modules/image/include/graph.h
rename to core/include/graph.h
index c3bdc0ae7..96bdb8638 100644
--- a/src/wasm/modules/image/include/graph.h
+++ b/core/include/graph.h
@@ -1,9 +1,10 @@
#ifndef GRAPH_H
#define GRAPH_H
-#include "node.h"
#include
+#include "node.h"
+
/*
Graph and Node classes support conversion of a region divided image into a
graph structure. Each Node represents a region of pixels which tracks the color
@@ -30,35 +31,37 @@ discover_edges(G, region_labels, width, height);
*/
class Graph {
-protected:
- int m_width, m_height;
- std::unique_ptr> m_nodes;
- std::unordered_map m_node_ids;
+ protected:
+ int m_width, m_height;
+ std::unique_ptr> m_nodes;
+ std::unordered_map m_node_ids;
- void hash_node_ids(void);
+ void hash_node_ids(void);
-public:
- inline Graph(std::unique_ptr> &nodes, int width,
- int height)
- : m_nodes(std::move(nodes)), m_width(width), m_height(height) {
- hash_node_ids();
- }
+ public:
+ inline Graph(std::unique_ptr> &nodes, int width, int height)
+ : m_nodes(std::move(nodes)), m_width(width), m_height(height) {
+ hash_node_ids();
+ }
- bool add_edge(int32_t node_id1, int32_t node_id2);
- bool merge_nodes(const Node_ptr &node_to_keep,
- const Node_ptr &node_to_remove);
+ bool add_edge(int32_t node_id1, int32_t node_id2);
+ bool merge_nodes(const Node_ptr &node_to_keep, const Node_ptr &node_to_remove);
- void clear_unconnected_nodes();
+ void clear_unconnected_nodes();
- inline const std::vector &get_nodes() const { return *m_nodes; }
+ inline const std::vector &get_nodes() const {
+ return *m_nodes;
+ }
- bool all_areas_bigger_than(int32_t min_area);
- inline const size_t size() { return m_nodes->size(); }
+ bool all_areas_bigger_than(int32_t min_area);
+ inline const size_t size() {
+ return m_nodes->size();
+ }
- void discover_edges(const std::vector ®ion_labels,
- const int32_t width, const int32_t height);
- void merge_small_area_nodes(const int32_t min_area);
- void compute_contours();
+ void discover_edges(const std::vector ®ion_labels, const int32_t width,
+ const int32_t height);
+ void merge_small_area_nodes(const int32_t min_area);
+ void compute_contours();
};
#endif
diff --git a/core/include/image_utils.h b/core/include/image_utils.h
new file mode 100644
index 000000000..db110da44
--- /dev/null
+++ b/core/include/image_utils.h
@@ -0,0 +1,8 @@
+#ifndef IMAGE_UTILS_H
+#define IMAGE_UTILS_H
+
+#include
+
+uint8_t quantize(uint8_t value, uint8_t region_size);
+
+#endif
diff --git a/core/include/node.h b/core/include/node.h
new file mode 100644
index 000000000..cee3243e0
--- /dev/null
+++ b/core/include/node.h
@@ -0,0 +1,130 @@
+#ifndef NODE_H
+#define NODE_H
+
+#include
+#include
+#include
+#include
+#include
+
+#include "RGBPixel.h"
+#include "contours.h"
+
+/*
+ Graph and Node classes support conversion of a region divided image into a
+graph structure. Each Node represents a region of pixels which tracks the color
+and coordinates (RGBXY) of belonging pixels, and its neighbors as edges.
+
+usage:
+
+std::vector nodes; // list of all nodes to be tracked
+
+std::unique_ptr> p_ptr =
+std::make_unique>(); // vector of pixels belonging to this
+region Node_ptr n_ptr = std::make_shared(, p_ptr);
+nodes.push_back(n_ptr);
+
+Graph manages a collection of nodes. It will take ownership of `nodes`.
+A graph is initialized as a list of disconnected nodes.
+
+std::unique_ptr> node_ptr =
+std::make_unique>(std::move(nodes)); Graph G(node_ptr);
+
+Given a region image, edges are discovered and recorded:
+discover_edges(G, region_labels, width, height);
+
+*/
+
+struct XY {
+ int32_t x, y;
+ std::pair xy;
+ XY(int32_t x_, int32_t y_) : x(x_), y(y_) {
+ xy = std::make_pair(x, y);
+ };
+ bool operator<(const XY &rhs) const {
+ return xy < rhs.xy;
+ };
+};
+
+struct RGBXY {
+ ImageLib::RGBPixel color;
+ XY position;
+
+ RGBXY(uint8_t r, uint8_t g, uint8_t b, int32_t x, int32_t y) : color(r, g, b), position{x, y} {
+ }
+};
+
+class Node;
+typedef std::shared_ptr Node_ptr;
+
+/*
+ *Node represents a region - collection of pixels, and their neighboring regions
+ *(edges)
+ */
+
+class Node {
+ protected:
+ int32_t m_id;
+ std::unique_ptr> m_pixels;
+ std::set m_edges{};
+
+ // pixels considered for contour tracing but not influencing other
+ // node properties such as color
+ std::set m_edge_pixels{};
+
+ public:
+ inline Node(int32_t id, std::unique_ptr> &pixels)
+ : m_id(id), m_pixels(std::move(pixels)) {
+ }
+
+ XY centroid() const;
+ ImageLib::RGBPixel color() const;
+ std::array bounding_box_xywh() const;
+ std::array create_binary_image(std::vector &binary) const;
+
+ // keep track of its own contour points
+ // only filled in when compute_contour() is called
+ // though these are public only Graph should access them
+ ColoredContours m_contours;
+ void clear_contour();
+ void compute_contour();
+
+ /* access member variables */
+ inline int32_t id() const {
+ return m_id;
+ };
+ inline size_t area() const {
+ return m_pixels->size();
+ };
+ inline const std::set &edges() const {
+ return m_edges;
+ }
+ inline size_t num_edges() const {
+ return m_edges.size();
+ }
+ inline const std::vector &get_pixels() const {
+ return *m_pixels;
+ }
+ inline ColoredContours &get_contours() {
+ return m_contours;
+ }
+
+ /* modify member variables */
+ void add_pixels(const std::vector &new_pixels);
+ void add_edge_pixel(const XY edge_pixel);
+ void clear_edge_pixels();
+
+ void clear_all();
+
+ inline void add_edge(const Node_ptr &node) {
+ m_edges.insert(node);
+ }
+ inline void remove_edge(const Node_ptr &node) {
+ m_edges.erase(node);
+ }
+ inline void remove_all_edges() {
+ m_edges.clear();
+ }
+};
+
+#endif
diff --git a/core/src/SavitskyGolay.cpp b/core/src/SavitskyGolay.cpp
new file mode 100644
index 000000000..09c0bc329
--- /dev/null
+++ b/core/src/SavitskyGolay.cpp
@@ -0,0 +1,135 @@
+#include "SavitskyGolay.h"
+
+#include
+#include
+#include
+#include
+
+SavitzkyGolay::SavitzkyGolay(int radius, int poly_order)
+ : window_radius_(radius), window_size_(2 * radius + 1), poly_order_(poly_order) {
+ assert(radius >= 0);
+ assert(window_size_ > poly_order_);
+
+ compute_coefficients();
+}
+
+std::vector SavitzkyGolay::filter(const std::vector &data) {
+ if (data.size() < window_size_) {
+ return data; // Data too short to filter
+ }
+
+ std::vector result(data.size());
+
+ // 1. Convolution for the valid range
+ for (size_t i = window_radius_; i < data.size() - window_radius_; ++i) {
+ Point val{0.0, 0.0};
+ for (int j = -window_radius_; j <= window_radius_; ++j) {
+ val += data[i + j] * coeffs_[j + window_radius_];
+ }
+ result[i] = val;
+ }
+
+ // 2. Handle Edges (Simple Repeat/Nearest padding strategy)
+ // For a robust production app, you might calculate asymmetric kernels here.
+ for (int i = 0; i < window_radius_; ++i) result[i] = data[i];
+ for (size_t i = data.size() - window_radius_; i < data.size(); ++i) result[i] = data[i];
+
+ return result;
+}
+
+std::vector SavitzkyGolay::filter_wrap(const std::vector &data) {
+ // wrap around
+ if (data.size() < window_size_) {
+ return data; // Data too short to filter
+ }
+
+ std::vector result(data.size());
+ std::copy(data.begin(), data.end(), result.begin());
+
+ for (size_t i = 0; i < data.size(); ++i) {
+ Point val{0.0, 0.0};
+ for (int j = -window_radius_; j <= window_radius_; ++j) {
+ int k = i + j;
+ if (k < 0) {
+ k = data.size() + k;
+ } else if (k >= data.size()) {
+ k = k - data.size();
+ }
+ val = val + data[k] * coeffs_[j + window_radius_];
+ }
+ result[i] = val;
+ }
+
+ return result;
+}
+
+// Helper: Invert a matrix using Gauss-Jordan Elimination
+// A is (N x N), returns A_inv
+std::vector> SavitzkyGolay::invert_matrix(std::vector> A) {
+ int n = A.size();
+ std::vector> inv(n, std::vector(n, 0.0));
+
+ // Initialize inverse as identity
+ for (int i = 0; i < n; ++i) inv[i][i] = 1.0;
+
+ for (int i = 0; i < n; ++i) {
+ // Find pivot
+ float pivot = A[i][i];
+ // (Simple pivot check, typically you'd swap rows for stability)
+ if (std::abs(pivot) < 1e-10) throw std::runtime_error("Matrix singular, cannot invert.");
+
+ // Normalize row
+ for (int j = 0; j < n; ++j) {
+ A[i][j] /= pivot;
+ inv[i][j] /= pivot;
+ }
+
+ // Eliminate other rows
+ for (int k = 0; k < n; ++k) {
+ if (k != i) {
+ float factor = A[k][i];
+ for (int j = 0; j < n; ++j) {
+ A[k][j] -= factor * A[i][j];
+ inv[k][j] -= factor * inv[i][j];
+ }
+ }
+ }
+ }
+ return inv;
+}
+
+void SavitzkyGolay::compute_coefficients() {
+ // 1. Create the matrix J = (A^T * A)
+ // Size is (poly_order + 1) x (poly_order + 1)
+ // Element J[i][j] is the sum of k^(i+j) for k in -m..m
+
+ int rows = poly_order_ + 1;
+ std::vector> J(rows, std::vector(rows));
+
+ for (int i = 0; i < rows; ++i) {
+ for (int j = 0; j < rows; ++j) {
+ float sum = 0;
+ for (int k = -window_radius_; k <= window_radius_; ++k) {
+ sum += std::pow(k, i + j);
+ }
+ J[i][j] = sum;
+ }
+ }
+
+ // 2. Invert J to solve the normal equations
+ auto J_inv = invert_matrix(J);
+
+ // 3. Compute the weights
+ // The smoothed value is the coefficient c_0 of the polynomial.
+ // c_0 = sum( weight_k * y_k )
+ // weight_k = sum( J_inv[0][j] * k^j ) for j=0..order
+
+ coeffs_.resize(window_size_);
+ for (int k = -window_radius_; k <= window_radius_; ++k) {
+ float weight = 0.0;
+ for (int j = 0; j < rows; ++j) {
+ weight += J_inv[0][j] * std::pow(k, j);
+ }
+ coeffs_[k + window_radius_] = weight;
+ }
+}
diff --git a/core/src/bezier.cpp b/core/src/bezier.cpp
new file mode 100644
index 000000000..86aedc725
--- /dev/null
+++ b/core/src/bezier.cpp
@@ -0,0 +1,152 @@
+#include "bezier.h"
+
+#include
+#include
+#include
+
+// --- Vector Math Helpers ---
+inline float dot(Point a, Point b) {
+ return a.x * b.x + a.y * b.y;
+}
+inline float len(Point a, Point b) {
+ Point c = a - b;
+ return std::sqrt(c.x * c.x + c.y * c.y);
+}
+
+// --- Evaluate Quadratic Bezier at t ---
+Point evalBezier(const QuadBezier &b, float t) {
+ // B(t) = (1-t)^2 * P0 + 2*t*(1-t) * P1 + t^2 * P2
+ float invT = 1.0 - t;
+ float c0 = invT * invT;
+ float c1 = 2.0f * t * invT;
+ float c2 = t * t;
+
+ return c0 * b.p0 + c1 * b.p1 + c2 * b.p2;
+}
+
+// --- Chord Length Parameterization ---
+// Assigns a 't' value (0.0 to 1.0) to each point based on distance
+std::vector chordLengthParameterize(const std::vector &points) {
+ std::vector u;
+ u.reserve(points.size());
+ u.push_back(0.0f);
+
+ for (int i = 1; i < points.size(); ++i) {
+ float dist = len(points[i], points[i - 1]);
+ u.push_back(u.back() + dist);
+ }
+
+ float totalLen = u.back();
+ if (totalLen == 0) return u; // Should not happen for valid ranges
+
+ for (float &val : u) {
+ val /= totalLen;
+ }
+ return u;
+}
+
+// --- Least Squares Fit for Control Point Q1 ---
+// We know Q0 (Start) and Q2 (End). We need to find Q1 that minimizes error.
+// Based on equation: P(t) = (1-t)^2 Q0 + 2t(1-t) Q1 + t^2 Q2
+// Rearranged: Q1 * [2t(1-t)] = P(t) - (1-t)^2 Q0 - t^2 Q2
+Point generateQuadBezier(const std::vector &points, const std::vector