Showing preview only (300K chars total). Download the full file or copy to clipboard to get everything.
Repository: imgly/background-removal-js
Branch: main
Commit: 12f56cc4f2a9
Files: 124
Total size: 268.9 KB
Directory structure:
gitextract_zf76w0ij/
├── .gitattributes
├── .github/
│ └── workflows/
│ └── pnpm-pr-check.yml
├── .gitignore
├── .husky/
│ └── pre-commit
├── .npmrc
├── .nvmrc
├── .prettierignore
├── .prettierrc.js
├── LICENSE.md
├── README.md
├── TODOS.md
├── bundle/
│ └── models/
│ ├── isnet
│ ├── isnet_fp16
│ └── isnet_quint8
├── package.json
├── packages/
│ ├── node/
│ │ ├── .resources.mjs
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE.md
│ │ ├── README.md
│ │ ├── ThirdPartyLicenses.json
│ │ ├── changelog/
│ │ │ ├── 1.2.0/
│ │ │ │ └── 20230811184244-export_type_and_formats.yml
│ │ │ ├── 1.2.1/
│ │ │ │ └── 20230811184244-Changelog_item.yml
│ │ │ ├── 1.3.0/
│ │ │ │ ├── 20230612112304-progress_return_type.yaml
│ │ │ │ ├── 20231512181521-resource_data_chunking.yaml
│ │ │ │ └── 20231512193816-upscale_mask_to_original_image.yaml
│ │ │ ├── 1.4.0/
│ │ │ │ ├── 20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml
│ │ │ │ ├── 20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml
│ │ │ │ ├── 20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
│ │ │ │ └── 20242301155647-Typescript_bindings_are_generated_with_tsc.yaml
│ │ │ ├── 1.4.5/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ ├── Unreleased/
│ │ │ │ └── .keep
│ │ │ └── info.yml
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ ├── build.mjs
│ │ │ └── watch.mjs
│ │ ├── src/
│ │ │ ├── codecs.ts
│ │ │ ├── index.ts
│ │ │ ├── inference.ts
│ │ │ ├── onnx.ts
│ │ │ ├── resource.ts
│ │ │ ├── schema.ts
│ │ │ ├── url.ts
│ │ │ └── utils.ts
│ │ └── tsconfig.json
│ ├── node-e2e/
│ │ ├── fixtures/
│ │ │ └── images/
│ │ │ └── img2img.sh
│ │ ├── package.json
│ │ └── src/
│ │ └── example.test.js
│ ├── node-examples/
│ │ ├── package.json
│ │ └── src/
│ │ └── example_001.cjs
│ ├── web/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE.md
│ │ ├── README.md
│ │ ├── ThirdPartyLicenses.json
│ │ ├── changelog/
│ │ │ ├── 1.2.0/
│ │ │ │ └── 20230811184244-export_type_and_formats.yml
│ │ │ ├── 1.2.1/
│ │ │ │ └── 20230811184244-Changelog_item.yml
│ │ │ ├── 1.3.0/
│ │ │ │ ├── 20230612112148-progress_return_type.yaml
│ │ │ │ ├── 20231512181521-resource_data_chunking.yaml
│ │ │ │ └── 20231512193816-upscale_mask_to_original_image.yaml
│ │ │ ├── 1.4.0/
│ │ │ │ ├── 20233012103509-Moved.yaml
│ │ │ │ ├── 20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml
│ │ │ │ ├── 20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml
│ │ │ │ ├── 20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
│ │ │ │ ├── 20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
│ │ │ │ ├── 20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml
│ │ │ │ └── 20242301155639-Typescript_bindings_are_generated_with_tsc.yaml
│ │ │ ├── 1.4.5/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ ├── 1.5.0/
│ │ │ │ ├── 20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml
│ │ │ │ └── 20242503170808-Added_isnet_model_for_webgpu_Added.yaml
│ │ │ ├── 1.5.6/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ ├── Unreleased/
│ │ │ │ └── .keep
│ │ │ └── info.yml
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ ├── build.mjs
│ │ │ └── watch.mjs
│ │ ├── src/
│ │ │ ├── MimeType.ts
│ │ │ ├── api/
│ │ │ │ └── v1.ts
│ │ │ ├── capabilities.js
│ │ │ ├── codecs.ts
│ │ │ ├── index.ts
│ │ │ ├── inference.ts
│ │ │ ├── onnx.ts
│ │ │ ├── resource.ts
│ │ │ ├── schema.ts
│ │ │ ├── types.d.ts
│ │ │ ├── url.ts
│ │ │ └── utils.ts
│ │ └── tsconfig.json
│ ├── web-data/
│ │ ├── .resources.mjs
│ │ ├── LICENSE.md
│ │ ├── ThirdPartyLicenses.json
│ │ ├── changelog/
│ │ │ ├── 1.4.5/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ └── 1.5.6/
│ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ └── package.json
│ └── web-examples/
│ ├── next-example/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── eslint.config.mjs
│ │ ├── next.config.ts
│ │ ├── package.json
│ │ ├── src/
│ │ │ └── app/
│ │ │ ├── BackgroundRemoval.tsx
│ │ │ ├── BackgroundRemovalNoSSR.tsx
│ │ │ ├── globals.css
│ │ │ ├── layout.tsx
│ │ │ └── page.tsx
│ │ └── tsconfig.json
│ └── vite-project/
│ ├── .gitignore
│ ├── .vercel/
│ │ ├── README.txt
│ │ └── project.json
│ ├── README.md
│ ├── index.html
│ ├── package.json
│ ├── src/
│ │ ├── App.vue
│ │ ├── main.ts
│ │ ├── style.css
│ │ └── vite-env.d.ts
│ ├── tsconfig.json
│ ├── tsconfig.node.json
│ └── vite.config.ts
├── pnpm-workspace.yaml
└── scripts/
├── changelog/
│ ├── changelog-create.mjs
│ ├── changelog-generate.mjs
│ └── template.yml.ejs
├── deploy-assets.mjs
├── package-resources.mjs
└── package-version.mjs
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
bundle/**/* filter=lfs diff=lfs merge=binary
**/*.onnx filter=lfs diff=lfs merge=binary
**/*.ort filter=lfs diff=lfs merge=binary
**/*.{jpeg,jpg} filter=lfs diff=lfs merge=binary
**/*.png filter=lfs diff=lfs merge=binary
**/*.webp filter=lfs diff=lfs merge=binary
**/*.avif filter=lfs diff=lfs merge=binary
**/*.heic filter=lfs diff=lfs merge=binary
**/*.heif filter=lfs diff=lfs merge=binary
**/*.pdf filter=lfs diff=lfs merge=binary
**/*.psd filter=lfs diff=lfs merge=binary
**/*.mp4 filter=lfs diff=lfs merge=binary
**/*.mov filter=lfs diff=lfs merge=binary
**/*.m4v filter=lfs diff=lfs merge=binary
**/*.mp3 filter=lfs diff=lfs merge=binary
**/*.wav filter=lfs diff=lfs merge=binary
**/*.aif filter=lfs diff=lfs merge=binary
**/*.aiff filter=lfs diff=lfs merge=binary
================================================
FILE: .github/workflows/pnpm-pr-check.yml
================================================
name: Build and test pnpm workspace
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build-and-test:
name: Build and test
uses: imgly/github-workflows/.github/workflows/pnpm-pr-check.yml@v1
secrets: inherit
================================================
FILE: .gitignore
================================================
node_modules
releases
dist
tmp
.DS_Store
.vscode
.parcel-cache
.env
================================================
FILE: .husky/pre-commit
================================================
================================================
FILE: .npmrc
================================================
; Allow transitive dependency type access
shamefully-hoist = true
; Hard error on unsatisfied peer dependency requirements
strict-peer-dependencies = true
; Prevent accidents when running actions with outdated node_modules
verify-deps-before-run = error
; Fix sync-dependencies-meta-injected crashing due to some dependencies not respecting the injected flag as an optimization
dedupe-injected-deps = false
================================================
FILE: .nvmrc
================================================
v20.17.0
================================================
FILE: .prettierignore
================================================
**/node_modules
**/dist
**/tmp
build
**/package-lock.json
.vscode/
**/public/**
CHANGELOG.md
================================================
FILE: .prettierrc.js
================================================
module.exports = {
singleQuote: true,
arrowParens: 'always',
trailingComma: 'none'
};
================================================
FILE: LICENSE.md
================================================
# GNU Affero General Public License
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. <<http://fsf.org/>>_
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
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.
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.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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
<<http://www.gnu.org/licenses/>>.
================================================
FILE: README.md
================================================
# Background Removal in the Browser & Node.js
### 🚨 We are hiring 🚨
We are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**
<p align="center">
<img src="https://storage.googleapis.com/imgly-static-assets/static/blog/github-releases/background-removal-free-plugin-app.jpg" alt="background removal js showcase" />
</p>
Remove backgrounds from images directly in the browser or Node.js environment with ease and no additional costs or privacy concerns.
Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).
## Overview
`@imgly/background-removal` is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser.
`@imgly/background-removal-node` is a powerful npm package that allows developers to remove the background from images in Node.js.
With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.
## Who is it for?
`@imgly/background-removal` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser or Node.js. It caters to a wide range of use cases, including but not limited to:
- _E-commerce applications_ that need to remove backgrounds from product images in real time.
- _Image editing applications_ that require background removal capabilities for enhancing user experience.
- _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal.
Whether you are a professional developer or a hobbyist, `@imgly/background-removal` empowers you to deliver impressive applications and services with ease.
## License
The software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal%20License) for questions about other licensing options.
## Authors & Contributors
This library is made by IMG.LY shipping the world's premier SDKs for building creative applications.
Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).
================================================
FILE: TODOS.md
================================================
# Todos
## Todo 2.0
- [ ] use logger/telemetry callback instead of custom debug output
- [ ] use resolver callback instead of publicPath as such we can allow various
```
resolve: (path: string) => Response
```
- [ ] default to `gpu`
- [ ] remove image encode and decode
- [ ] removebg should get `ImageData` and return raw `ImageData`
================================================
FILE: bundle/models/isnet
================================================
version https://git-lfs.github.com/spec/v1
oid sha256:cc2c9f5c1751b9737cb81e708ff0c5e9542c2205daed22418a4fd2ab5d4c481a
size 176149806
================================================
FILE: bundle/models/isnet_fp16
================================================
version https://git-lfs.github.com/spec/v1
oid sha256:2eb4b5dda7ec41c617e59706e5aafa1f978c9a5f983d2518d9f0ae4d6eb04f20
size 88152708
================================================
FILE: bundle/models/isnet_quint8
================================================
version https://git-lfs.github.com/spec/v1
oid sha256:d1ca3535c21b53d08fa3b640e5949389f82e764f6376a0502d44982c35cae482
size 44348940
================================================
FILE: package.json
================================================
{
"version": "1.7.0",
"name": "workspace",
"private": true,
"bin": {
"changelog-create": "./scripts/changelog/changelog-create.mjs",
"changelog-generate": "./scripts/changelog/changelog-generate.mjs"
},
"files": [],
"scripts": {
"start": "pnpm run watch",
"watch": "concurrently \"pnpm run watch --prefix packages/web\" \"pnpm run watch --prefix packages/node\"",
"build": "pnpm recursive run build",
"lint:fix": "npx prettier -c -w --ignore-unknown .",
"lint:check": "npx prettier -c --ignore-unknown .",
"publish:latest": "pnpm run publish:latest --workspaces --if-present && pnpm run deploy-assets",
"publish:next": "pnpm run publish:next --workspaces --if-present && pnpm run deploy-assets",
"package:version": "node ./scripts/package-version.mjs",
"deploy-assets": "node -r dotenv/config ./scripts/deploy-assets.mjs",
"tag": "git tag $npm_package_version & git push origin $npm_package_version",
"package:pack": "pnpm run package:pack --workspaces --if-present",
"prepare": "husky"
},
"devDependencies": {
"chalk": "~5.3.0",
"concurrently": "~8.2.2",
"dotenv": "~16.3.1",
"ejs": "~3.1.9",
"es-main": "~1.3.0",
"esbuild": "^0.21.1",
"glob": "~10.3.3",
"husky": "^9.0.11",
"lint-staged": "^15.2.2",
"meow": "~13.0.0",
"moment": "~2.29.4",
"onchange": "~7.1.0",
"prettier": "^3.5.3",
"rimraf": "^6.0.1",
"yaml": "~2.3.4"
},
"packageManager": "pnpm@10.6.5+sha512.cdf928fca20832cd59ec53826492b7dc25dc524d4370b6b4adbf65803d32efaa6c1c88147c0ae4e8d579a6c9eec715757b50d4fa35eea179d868eada4ed043af"
}
================================================
FILE: packages/node/.resources.mjs
================================================
export default [
{
path: '/models/',
source: '../../bundle/models/*',
mime: 'application/octet-steam'
}
];
================================================
FILE: packages/node/CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.4.5]
### Added
- Added ThirdPartyLicenses.json
## [1.4.0]
### Added
- Bumped onnx runtime to 1.17 Changed
- Changed license from GPL to AGPL Changed
- Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.
### Changed
- Typescript bindings are generated with tsc
## [1.3.0]
### Added
- Resources are now chunked to 4MB for better caching performance and download restart.
- Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.
- Config option to export 'x-alpha8' format to get receive single channel alpha mask.
### Removed
- Configuration options to specify if background, foreground or mask is exported.
### Changed
- Changed the return value type of the progress callback from undefined to void
- Output is now in the original image size. Mask is upscaled and applied to the original image.
## [1.2.1]
### Added
- `CHANGELOG.md` for an better overview of the changes.
- support for raw `rgba8` export formats.
## [1.2.0]
### Added
- Support `foreground`, `background` and `mask` export type.
- Added support for `webp` and `jpeg` export formats.
================================================
FILE: packages/node/LICENSE.md
================================================
# GNU Affero General Public License
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. <<http://fsf.org/>>_
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
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.
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.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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
<<http://www.gnu.org/licenses/>>.
================================================
FILE: packages/node/README.md
================================================
# Background Removal in NodeJs
### 🚨 We are hiring 🚨
We are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**
<p align="center">
<img src="https://img.ly/showcases/cesdk/web/s/case-thumbnail/background-removal/background-removal-0.png?utm_source=github&utm_medium=project&utm_campaign=background-removal-js" alt="background removal js showcase" />
</p>
Remove backgrounds from images in NodeJs environment with ease and no additional costs or privacy concerns.
Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).
## News
- **`July 18th, 2025`:** Updated to use stable ONNX runtime version 1.21.0 instead of dev version.
- **`November 8th, 2023`:** Added support for raw `rgba8` export formats.
- **`November 6th, 2023`:** Added support `foreground`, `background` and `mask` export type
- **`November 6th, 2023`:** Added support for `webp` and `jpeg` export formats.
- **`September 12th, 2023`:** We released the code of Background Removal NodeJS.
For more detail information please refer to the [CHANGELOG](./CHANGELOG.md).
## Overview
`@imgly/background-removal-node` is a powerful npm package that allows developers to seamlessly remove the background from images in NodeJs. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.
The key features of `@imgly/background-removal-node` are:
- **Seamless Integration with IMG.LY's CE.SDK**: `@imgly/background-removal-node` provides seamless integration with [IMG.LY's CE.SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), allowing developers to easily incorporate powerful NodeJS image matting and background removal capabilities into their projects.
The Neural Network model files ([ONNX model](https://onnx.ai/)) are hosted by [IMG.LY](https://img.ly/), making it readily available for download to all users of the library. See the section Custom Asset Serving if you want to host data on your own servers.
## Installation
You can install `@imgly/background-removal-node` via npm or yarn. Use the following commands to install the package:
### NPM
```shell
npm install @imgly/background-removal-node
```
## Usage
```typescript
import {removeBackground} from "@imgly/background-removal-node";
// const {removeBackground} = require("@imgly/background-removal-node");
let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;
removeBackground(image_src).then((blob: Blob) => {
// The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src
})
```
Note: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache.
## Advanced Configuration
The library does not need any configuration to get started. However, there are optional parameters that influence the behaviour and give more control over the library.
```typescript
type Config = {
publicPath: string; // The public path used for model and wasm files. Default: '`file://${path.resolve(`node_modules/${pkg.name}/dist/`)}/`.
debug: bool; // enable or disable useful console.log outputs
model: 'small' | 'medium'; // The model to use. (Default "medium")
output: {
format: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/x-rgba8'; // The output format. (Default "image/png")
quality: number; // The quality. (Default: 0.8)
type: 'foreground' | 'background' | 'mask'; // The output type. (Default "foreground")
};
};
```
### Download Size vs Quality
The onnx model is shipped in various sizes and needs.
- small (~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It's a quantized model.
- medium (~80MB) is the default model.
### Download Progress Monitoring
On the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress.
```typescript
let config: Config = {
progress: (key, current, total) => {
console.log(`Downloading ${key}: ${current} of ${total}`);
}
};
```
### Custom Asset Serving
The wasm and onnx neural networks are hosted by IMG.LY by default. For production use, we advise you to host them yourself. Therefore, copy all .wasm and .onnx files to your public path `$PUBLIC_PATH` and reconfigure the library.
```shell
cp node_modules/@imgly/background-removal-node/dist/*.* $PUBLIC_PATH
```
```typescript
import { removeBackground, Config} from "@imgly/background-removal-node"
const public_path = "file://${ASSET_PATH}" ; // the path on the local file system
//const public_path = "https://example.com/assets/" ; // the path assets are served from
let config: Config = {
publicPath: public_path, // path to the wasm files
};
let image_src: Buffer | ArrayBuffer | Uint8Array | Blob | URL | string = ...;
removeBackground(image_src, config).then((blob: Blob) => {
// result is a blob encoded as PNG.
// It can be converted to an URL to be used as HTMLImage.src
const url = URL.createObjectURL(blob);
})
```
### Debug Outputs
Enable debug outputs and logging to the console
```typescript
let config: Config = {
debug: true
};
```
### Cross-Origin Resource Sharing (CORS)
If you are running into CORS issues you might want to pass additional parameters to the fetch function via
```typescript
let config: Config = {
fetchArgs: {
mode: 'no-cors'
}
};
```
`fetchArgs` are passed as second parameters to the fetch function as described in [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
## Who is it for?
`@imgly/background-removal-node` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to:
- _E-commerce applications_ that need to remove backgrounds from product images in real time.
- _Image editing applications_ that require background removal capabilities for enhancing user experience.
- _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal.
Whether you are a professional developer or a hobbyist, `@imgly/background-removal-node` empowers you to deliver impressive applications and services with ease.
## License
The software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal-Node%20License) for questions about other licensing options.
## Authors & Contributors
This library is made by IMG.LY shipping the world's premier SDKs for building creative applications.
Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js-node).
================================================
FILE: packages/node/ThirdPartyLicenses.json
================================================
{
"onnxruntime-web": {
"source": "https://www.npmjs.com/package/onnxruntime-node",
"type": "code",
"license": "MIT"
},
"ISNET": {
"source": "https://github.com/xuebinqin/DIS",
"type": "model",
"license": "MIT"
}
}
================================================
FILE: packages/node/changelog/1.2.0/20230811184244-export_type_and_formats.yml
================================================
---
type: Added
description: Support `foreground`, `background` and `mask` export type.
---
type: Added
description: Added support for `webp` and `jpeg` export formats.
================================================
FILE: packages/node/changelog/1.2.1/20230811184244-Changelog_item.yml
================================================
---
type: Added
description: |
`CHANGELOG.md` for an better overview of the changes.
---
type: Added
description: |
support for raw `rgba8` export formats.
================================================
FILE: packages/node/changelog/1.3.0/20230612112304-progress_return_type.yaml
================================================
---
type: Changed
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Changed the return value type of the progress callback from undefined to void
================================================
FILE: packages/node/changelog/1.3.0/20231512181521-resource_data_chunking.yaml
================================================
---
type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Resources are now chunked to 4MB for better caching performance and download restart.
================================================
FILE: packages/node/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml
================================================
---
type: Changed
# type: Removed
# type: Security
# private: true
description: |
Output is now in the original image size. Mask is upscaled and applied to the original image.
---
type: Added
# type: Removed
# type: Security
# private: true
description: |
Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.
---
type: Removed
# type: Removed
# type: Security
# private: true
description: |
Configuration options to specify if background, foreground or mask is exported.
---
type: Added
# type: Removed
# type: Security
# private: true
description: |
Config option to export 'x-alpha8' format to get receive single channel alpha mask.
================================================
FILE: packages/node/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Bumped onnx runtime to 1.17 Changed
================================================
FILE: packages/node/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Changed license from GPL to AGPL Changed
================================================
FILE: packages/node/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.
================================================
FILE: packages/node/changelog/1.4.0/20242301155647-Typescript_bindings_are_generated_with_tsc.yaml
================================================
---
type: Changed
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Typescript bindings are generated with tsc
================================================
FILE: packages/node/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added ThirdPartyLicenses.json
================================================
FILE: packages/node/changelog/Unreleased/.keep
================================================
================================================
FILE: packages/node/changelog/info.yml
================================================
---
description: |
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
================================================
FILE: packages/node/package.json
================================================
{
"name": "@imgly/background-removal-node",
"version": "1.7.0",
"description": "Background Removal in NodeJS",
"resources": "@imgly/background-removal-node",
"keywords": [
"background-removal",
"nodejs",
"image-segmentation",
"image-matting",
"onnx"
],
"repository": {
"type": "git",
"url": "git+https://github.com/imgly/background-removal-js.git"
},
"license": "SEE LICENSE IN LICENSE.md",
"author": {
"name": "IMG.LY GmbH",
"email": "support@img.ly",
"url": "https://img.ly"
},
"bugs": {
"email": "support@img.ly"
},
"homepage": "https://img.ly/showcases/cesdk/web/background-removal",
"source": "./src/index.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts"
}
},
"files": [
"LICENSE.md",
"README.md",
"CHANGELOG.md",
"ThirdPartyLicenses.json",
"dist/",
"bin/"
],
"scripts": {
"start": "pnpm run watch",
"clean": "npx rimraf dist",
"test": "true",
"resources": "node ../../scripts/package-resources.mjs",
"changelog:create": "node ../../scripts/changelog/changelog-create.mjs",
"changelog:generate": "node ../../scripts/changelog/changelog-generate.mjs",
"build": "pnpm run clean && pnpm run resources && pnpm run types && pnpm run changelog:generate && node scripts/build.mjs",
"types": "tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap",
"watch": "pnpm run clean && pnpm run resources && pnpm run changelog:generate && node scripts/watch.mjs",
"check:all": "pnpm run check:pretty",
"check:pretty": "prettier --list-different './src/**/*.{ts,tsx}'",
"pretty": "prettier --write './src/**/*.{ts,tsx}'",
"publish:latest": "pnpm publish --tag latest --access public",
"publish:next": "pnpm publish --tag next --access public",
"package:pack": "pnpm pack . --pack-destination ../../releases"
},
"dependencies": {
"@types/lodash": "~4.14.195",
"@types/ndarray": "~1.0.14",
"@types/node": "~20.3.1",
"lodash": "~4.17.21",
"ndarray": "~1.0.19",
"onnxruntime-node": "1.21.0",
"sharp": "~0.32.4",
"zod": "^3.23.8"
},
"devDependencies": {
"assert": "~2.0.0",
"esbuild": "~0.18.18",
"npm-dts": "~1.3.12",
"os-browserify": "~0.3.0",
"path-browserify": "~1.0.1",
"process": "~0.11.10",
"stream-browserify": "~3.0.0",
"ts-loader": "~9.4.3",
"tslib": "~2.5.3",
"typescript": "~5.1.6",
"util": "~0.12.5",
"webpack": "~5.85.1",
"webpack-cli": "~5.1.4"
}
}
================================================
FILE: packages/node/scripts/build.mjs
================================================
export { configs };
import * as esbuild from 'esbuild';
import { readFileSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(
readFileSync(path.resolve(__dirname, '../package.json'))
);
const dependencies = Object.keys(pkg.dependencies);
const configs = [
{
entryPoints: ['src/index.ts'],
bundle: true,
sourcemap: true,
platform: 'node',
format: 'cjs',
external: dependencies,
outfile: 'dist/index.cjs'
},
{
entryPoints: ['src/index.ts'],
bundle: true,
sourcemap: true,
external: dependencies,
platform: 'node',
format: 'esm',
outfile: 'dist/index.mjs'
}
];
await configs.map(async (config) => await esbuild.build(config));
================================================
FILE: packages/node/scripts/watch.mjs
================================================
import * as esbuild from 'esbuild';
import { configs } from './build.mjs';
import dts from 'npm-dts';
new dts.Generator({
entry: 'src/index.ts',
output: 'dist/index.d.ts'
}).generate();
const contexts = await Promise.all(
configs.map((config) => esbuild.context(config))
);
await Promise.any(contexts.map((ctx) => ctx.watch()));
console.log('watching...');
================================================
FILE: packages/node/src/codecs.ts
================================================
export { imageEncode, imageDecode, MimeType };
import sharp, { FormatEnum } from 'sharp';
import ndarray, { NdArray } from 'ndarray';
async function imageDecode(blob: Blob): Promise<NdArray<Uint8Array>> {
const buffer = await blob.arrayBuffer();
const mime = MimeType.fromString(blob.type);
switch (mime.type) {
case 'image/x-alpha8': {
const width = parseInt(mime.params['width']);
const height = parseInt(mime.params['height']);
return ndarray(new Uint8Array(await blob.arrayBuffer()), [
height,
width,
1
]);
}
case 'image/x-rgba8': {
const width = parseInt(mime.params['width']);
const height = parseInt(mime.params['height']);
return ndarray(new Uint8Array(await blob.arrayBuffer()), [
height,
width,
4
]);
}
case 'application/octet-stream':
case `image/png`:
case `image/jpeg`:
case `image/jpg`:
case `image/webp`: {
const decoded = sharp(buffer);
let { width, height, channels } = await decoded.metadata();
if (channels === 3) {
decoded.ensureAlpha();
channels = 4;
}
const outBuffer = await decoded.raw().toBuffer();
const array = ndarray(outBuffer, [height!, width!, channels!]);
await sharp(array.data, {
raw: { width: width!, height: height!, channels: channels! }
});
return array;
}
default:
throw new Error(`Unsupported format: ${mime.type}`);
}
}
async function imageEncode(
imageTensor: NdArray<Uint8Array>,
quality: number = 0.8,
type: string = 'image/png'
): Promise<Blob> {
const [height, width, channels] = imageTensor.shape;
if (channels !== 4) throw new Error('Only 4-channel images are supported');
const image = sharp(imageTensor.data, { raw: { height, width, channels } });
type Keys = keyof FormatEnum;
switch (type) {
case 'image/x-alpha8':
case 'image/x-rgba8': {
const mime = MimeType.create(type, {
width: width.toString(),
height: height.toString()
});
return new Blob([imageTensor.data], { type: mime.toString() });
}
case `image/png`:
case `image/jpeg`:
case `image/webp`:
const format = type.split('/').pop()! as Keys;
const buffer = await image
.toFormat(format, { quality: quality * 100 })
.toBuffer();
return new Blob([buffer], { type: type });
default:
throw new Error(`Invalid format: ${format}`);
}
}
class MimeType {
type: string = 'application/octet-stream';
params: Record<string, string> = {};
private constructor(type: string, params: Record<string, string>) {
this.type = type;
this.params = params;
}
toString(): string {
const paramsStr = [];
for (const key in this.params) {
const value = this.params[key];
paramsStr.push(`${key}=${value}`);
}
return [this.type, ...paramsStr].join(';');
}
static create(type, params: Record<string, string>): MimeType {
return new MimeType(type, params);
}
isIdentical(other: MimeType): Boolean {
return this.type === other.type && this.params === other.params;
}
isEqual(other: MimeType): Boolean {
return this.type === other.type;
}
static fromString(mimeType: string): MimeType {
const [type, ...paramsArr] = mimeType.split(';');
const params: Record<string, string> = {};
for (const param of paramsArr) {
const [key, value] = param.split('=');
params[key.trim()] = value.trim();
}
return new MimeType(type, params);
}
}
================================================
FILE: packages/node/src/index.ts
================================================
export default removeBackground;
export {
removeBackground,
removeForeground,
segmentForeground,
applySegmentationMask
};
export type { Config, ImageSource };
import lodash from 'lodash';
import ndarray from 'ndarray';
import { initInference, runInference } from './inference';
import { Config, validateConfig } from './schema';
import * as utils from './utils';
import { ImageSource } from './utils';
const { memoize } = lodash;
const init = memoize(initInference, (config) => JSON.stringify(config));
/**
* Removes the background from an image.
*
* @param image - The image to remove the background from.
* @param configuration - Optional configuration for the background removal process.
* @returns A Promise that resolves to the resulting image with the background removed.
*/
async function removeBackground(
image: ImageSource,
configuration?: Config
): Promise<Blob> {
const { config, session } = await init(configuration);
const imageTensor = await utils.imageSourceToImageData(image, config);
const [width, height, channels] = imageTensor.shape;
const alphamask = await runInference(imageTensor, config, session);
const stride = width * height;
const outImageTensor = imageTensor;
for (let i = 0; i < stride; i += 1) {
outImageTensor.data[4 * i + 3] = alphamask.data[i];
}
const outImage = await utils.imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
/**
* Removes the foreground from an image.
*
* @param image - The image to remove the foreground from.
* @param configuration - Optional configuration for the foreground removal process.
* @returns A Promise that resolves to the resulting image with the foreground removed.
*/
async function removeForeground(
image: ImageSource,
configuration?: Config
): Promise<Blob> {
const { config, session } = await init(configuration);
const imageTensor = await utils.imageSourceToImageData(image, config);
const [width, height, channels] = imageTensor.shape;
const alphamask = await runInference(imageTensor, config, session);
const stride = width * height;
const outImageTensor = imageTensor;
for (let i = 0; i < stride; i += 1) {
outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i];
}
const outImage = await utils.imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
/**
* Segments the foreground of an image using a given configuration.
*
* @param image - The image source to segment.
* @param configuration - The optional configuration for the segmentation.
* @returns A Promise that resolves to the segmented foreground as a Blob.
*/
async function segmentForeground(
image: ImageSource,
configuration?: Config
): Promise<Blob> {
const { config, session } = await init(configuration);
const imageTensor = await utils.imageSourceToImageData(image, config);
const [height, width, channels] = imageTensor.shape;
const alphamask = await runInference(imageTensor, config, session);
const stride = width * height;
if (config.output.format === 'image/x-alpha8') {
const outImage = await utils.imageEncode(
alphamask,
config.output.quality,
config.output.format
);
return outImage;
} else {
const outImageTensor = ndarray(new Uint8Array(channels * stride), [
height,
width,
channels
]);
for (let i = 0; i < stride; i += 1) {
const index = 4 * i + 3;
outImageTensor.data[index] = alphamask.data[i]; //Red
outImageTensor.data[index + 1] = alphamask.data[i]; //Green
outImageTensor.data[index + 2] = alphamask.data[i]; // Blue
outImageTensor.data[index + 3] = 255;
}
const outImage = await utils.imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
}
async function applySegmentationMask(
image,
mask,
config?: Config
): Promise<Blob> {
config = validateConfig(config);
const imageTensor = await utils.imageSourceToImageData(image, config);
const [imageHeight, imageWidth, imageChannels] = imageTensor.shape;
const maskTensor = await utils.imageSourceToImageData(mask, config);
const [maskHeight, maskWidth, maskChannels] = maskTensor.shape;
const alphaMask =
maskHeight !== imageHeight || maskWidth !== imageWidth
? utils.tensorResizeBilinear(maskTensor, imageWidth, imageHeight)
: maskTensor;
const stride = imageWidth * imageHeight;
for (let i = 0; i < stride; i += 1) {
const idxImage = imageChannels * i;
const idxMask = maskChannels * i;
imageTensor.data[idxImage + 3] = alphaMask.data[idxMask]; // alpha information it always in the first (sometimes also in the others)
}
const outImage = await utils.imageEncode(
imageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
================================================
FILE: packages/node/src/inference.ts
================================================
export { initInference, runInference };
import { tensorResizeBilinear, tensorHWCtoBCHW } from './utils';
import { createOnnxSession, runOnnxSession } from './onnx';
import { Config, validateConfig } from './schema';
import { loadAsBlob } from './resource';
import ndarray, { NdArray } from 'ndarray';
import { convertFloat32ToUint8 } from './utils';
async function initInference(config?: Config) {
config = validateConfig(config);
if (config.debug) console.debug('Loading model...');
const model = config.model;
const blob = await loadAsBlob(`/models/${model}`, config);
const arrayBuffer = await blob.arrayBuffer();
const session = await createOnnxSession(arrayBuffer, config);
return { config, session };
}
async function runInference(
imageTensor: NdArray<Uint8Array>,
config: Config,
session: any
): Promise<NdArray<Uint8Array>> {
if (config.progress) config.progress('compute:inference', 0, 1);
const resolution = 1024;
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
let tensorImage = tensorResizeBilinear(imageTensor, resolution, resolution);
const inputTensor = tensorHWCtoBCHW(tensorImage); // this converts also from float to rgba
// run
const predictionsDict = await runOnnxSession(
session,
[['input', inputTensor]],
['output']
);
let alphamask = ndarray(predictionsDict[0].data, [resolution, resolution, 1]);
let alphamaskU8 = convertFloat32ToUint8(alphamask);
alphamaskU8 = tensorResizeBilinear(alphamaskU8, srcWidth, srcHeight);
if (config.progress) config.progress('compute:inference', 1, 1);
return alphamaskU8;
}
================================================
FILE: packages/node/src/onnx.ts
================================================
export { createOnnxSession, runOnnxSession };
import ndarray, { NdArray } from 'ndarray';
import * as ort from 'onnxruntime-node';
// import * as ort from 'onnxruntime-node-gpu';
import { Config } from './schema';
async function createOnnxSession(model: any, config: Config) {
if (config.debug) {
ort.env.debug = true;
ort.env.logLevel = 'verbose';
console.debug('ort.env.wasm:', ort.env.wasm);
}
const ort_config: ort.InferenceSession.SessionOptions = {
graphOptimizationLevel: 'all',
executionMode: 'parallel'
};
const session = await ort.InferenceSession.create(model, ort_config).catch(
(e: any) => {
throw new Error(
`Failed to create session: ${e}. Please check if the publicPath is set correctly.`
);
}
);
return session;
}
async function runOnnxSession(
session: any,
inputs: [string, NdArray<Float32Array>][],
outputs: [string]
) {
const feeds: Record<string, any> = {};
for (const [key, tensor] of inputs) {
feeds[key] = new ort.Tensor(
'float32',
new Float32Array(tensor.data),
tensor.shape
);
}
const outputData = await session.run(feeds, {});
const outputKVPairs: NdArray<Float32Array>[] = [];
for (const key of outputs) {
const output: ort.Tensor = outputData[key];
const shape: number[] = output.dims as number[];
const data: Float32Array = output.data as Float32Array;
const tensor = ndarray(data, shape);
outputKVPairs.push(tensor);
}
return outputKVPairs;
}
================================================
FILE: packages/node/src/resource.ts
================================================
export { loadAsBlob, loadAsUrl, loadFromURI };
import { Config } from './schema';
import { ensureAbsoluteURI } from './url';
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
async function loadAsUrl(url: string, config: Config) {
return URL.createObjectURL(await loadAsBlob(url, config));
}
async function loadFromURI(
uri: URL,
config = { headers: { 'Content-Type': 'application/octet-stream' } }
) {
switch (uri.protocol) {
case 'http:':
return await fetch(uri);
case 'https:':
return await fetch(uri);
case 'file:': {
const buffer = await readFile(fileURLToPath(uri));
return new Response(buffer, { status: 200, headers: config.headers });
}
default:
throw new Error(`Unsupported protocol: ${uri.protocol}`);
}
}
async function loadAsBlob(key: string, config: Config) {
// load resource metadata
const resourceUri = ensureAbsoluteURI('./resources.json', config.publicPath);
const resourceResponse = await loadFromURI(resourceUri);
if (!resourceResponse.ok) {
throw new Error(
`Resource metadata not found. Ensure that the config.publicPath is configured correctly.`
);
}
const resourceMap = await resourceResponse.json();
const entry = resourceMap[key];
if (!entry) {
throw new Error(
`Resource ${key} not found. Ensure that the config.publicPath is configured correctly.`
);
}
const chunks = entry.chunks; // list of entries
let downloadedSize = 0;
const responses = chunks.map(async (chunk) => {
const url = ensureAbsoluteURI(chunk.hash, config.publicPath);
const chunkSize = chunk.offsets[1] - chunk.offsets[0];
const response = await loadFromURI(url, {
headers: { 'Content-Type': entry.mime }
});
const blob = await response.blob();
if (chunkSize !== blob.size) {
throw new Error(
`Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}`
);
}
if (config.progress) {
downloadedSize += chunkSize;
config.progress(`fetch:${key}`, downloadedSize, entry.size);
}
return blob;
});
// we could create a new buffer here and use the chunk entries and combine the file instead
const allChunkData = await Promise.all(responses);
const data = new Blob(allChunkData, { type: entry.mime });
if (data.size !== entry.size) {
throw new Error(
`Failed to fetch ${key} with size ${entry.size} but got ${data.size}`
);
}
return data;
}
================================================
FILE: packages/node/src/schema.ts
================================================
export { ConfigSchema, Config, validateConfig };
import { z } from 'zod';
import path from 'node:path';
import pkg from '../package.json';
function isURI(s: string) {
try {
new URL(s);
return true;
} catch (err) {
return false;
}
}
const ConfigSchema = z
.object({
publicPath: z
.string()
.optional()
.describe('The public path to the wasm files and the onnx model.')
.default(`file://${path.resolve(`node_modules/${pkg.name}/dist/`)}/`)
.transform((val) => {
return val
.replace('${PACKAGE_NAME}', pkg.name)
.replace('${PACKAGE_VERSION}', pkg.version);
})
.refine((val) => isURI(val), {
message: 'String must be a valid uri'
}),
debug: z
.boolean()
.default(false)
.describe('Whether to enable debug logging.'),
proxyToWorker: z
.boolean()
.default(true)
.describe('Whether to proxy inference to a web worker.'),
fetchArgs: z
.any({})
.default({})
.describe('Arguments to pass to fetch when loading the model.'),
progress: z
.function()
.args(z.string(), z.number(), z.number())
.returns(z.void())
.describe('Progress callback.')
.optional(),
model: z
.preprocess(
(val) => {
switch (val) {
case 'large':
return 'isnet';
case 'small':
return 'isnet_quint8';
case 'medium':
return 'isnet_fp16';
default:
return val;
}
},
z.enum(['isnet', 'isnet_fp16', 'isnet_quint8'])
)
.default('medium'),
output: z
.object({
format: z
.enum([
'image/png',
'image/jpeg',
'image/webp',
'image/x-rgba8',
'image/x-alpha8'
])
.default('image/png'),
quality: z.number().default(0.8)
})
.default({})
})
.default({})
.transform((config) => {
if (config.debug) console.log('Config:', config);
if (config.debug && !config.progress) {
config.progress =
config.progress ??
((key, current, total) => {
console.debug(`Downloading ${key}: ${current} of ${total}`);
});
}
return config;
});
type Config = z.infer<typeof ConfigSchema>;
function validateConfig(configuration?: Config): Config {
return ConfigSchema.parse(configuration ?? {});
}
================================================
FILE: packages/node/src/url.ts
================================================
export { ensureAbsoluteURI };
function isAbsoluteURI(url: string): boolean {
const regExp = new RegExp('^(?:[a-z+]+:)?//', 'i');
return regExp.test(url); // true - regular http absolute URL
}
function ensureAbsoluteURI(url: string, baseUrl: string): URL {
if (isAbsoluteURI(url)) {
return new URL(url);
} else {
return new URL(url, baseUrl);
}
}
================================================
FILE: packages/node/src/utils.ts
================================================
export {
imageDecode,
imageEncode,
tensorResizeBilinear,
tensorHWCtoBCHW,
calculateProportionalSize,
imageSourceToImageData,
ImageSource,
convertFloat32ToUint8
};
import { Config } from './schema';
import * as codecs from './codecs';
import { ensureAbsoluteURI } from './url';
import { loadFromURI } from './resource';
import ndarray, { NdArray } from 'ndarray';
import { imageDecode, imageEncode } from './codecs';
type ImageSource =
| ArrayBuffer
| Uint8Array
| Blob
| URL
| string
| NdArray<Uint8Array>;
function tensorResizeBilinear(
imageTensor: NdArray<Uint8Array>,
newWidth: number,
newHeight: number
): NdArray<Uint8Array> {
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
// Calculate the scaling factors
const scaleX = srcWidth / newWidth;
const scaleY = srcHeight / newHeight;
// Create a new NdArray to store the resized image
const resizedImageData = ndarray(
new Uint8Array(srcChannels * newWidth * newHeight),
[newHeight, newWidth, srcChannels]
);
// Perform interpolation to fill the resized NdArray
for (let y = 0; y < newHeight; y++) {
for (let x = 0; x < newWidth; x++) {
const srcX = x * scaleX;
const srcY = y * scaleY;
const x1 = Math.max(Math.floor(srcX), 0);
const x2 = Math.min(Math.ceil(srcX), srcWidth - 1);
const y1 = Math.max(Math.floor(srcY), 0);
const y2 = Math.min(Math.ceil(srcY), srcHeight - 1);
const dx = srcX - x1;
const dy = srcY - y1;
for (let c = 0; c < srcChannels; c++) {
const p1 = imageTensor.get(y1, x1, c);
const p2 = imageTensor.get(y1, x2, c);
const p3 = imageTensor.get(y2, x1, c);
const p4 = imageTensor.get(y2, x2, c);
// Perform bilinear interpolation
const interpolatedValue =
(1 - dx) * (1 - dy) * p1 +
dx * (1 - dy) * p2 +
(1 - dx) * dy * p3 +
dx * dy * p4;
resizedImageData.set(y, x, c, Math.round(interpolatedValue));
}
}
}
return resizedImageData;
}
function tensorHWCtoBCHW(
imageTensor: NdArray<Uint8Array>,
mean: number[] = [128, 128, 128],
std: number[] = [256, 256, 256]
): NdArray<Float32Array> {
var imageBufferData = imageTensor.data;
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
const stride = srcHeight * srcWidth;
const float32Data = new Float32Array(3 * stride);
// r_0, r_1, .... g_0,g_1, .... b_0
for (let i = 0, j = 0; i < imageBufferData.length; i += 4, j += 1) {
float32Data[j] = (imageBufferData[i] - mean[0]) / std[0];
float32Data[j + stride] = (imageBufferData[i + 1] - mean[1]) / std[1];
float32Data[j + stride + stride] =
(imageBufferData[i + 2] - mean[2]) / std[2];
}
return ndarray(float32Data, [1, 3, srcHeight, srcWidth]);
}
function calculateProportionalSize(
originalWidth: number,
originalHeight: number,
maxWidth: number,
maxHeight: number
): [number, number] {
const widthRatio = maxWidth / originalWidth;
const heightRatio = maxHeight / originalHeight;
const scalingFactor = Math.min(widthRatio, heightRatio);
const newWidth = Math.floor(originalWidth * scalingFactor);
const newHeight = Math.floor(originalHeight * scalingFactor);
return [newWidth, newHeight];
}
async function imageSourceToImageData(
image: ImageSource,
_: Config
): Promise<NdArray<Uint8Array>> {
if (typeof image === 'string') {
image = ensureAbsoluteURI(image, `file://${process.cwd()}/`);
}
if (image instanceof URL) {
image = await (await loadFromURI(image)).blob();
}
if (image instanceof ArrayBuffer || ArrayBuffer.isView(image)) {
image = new Blob([image]);
}
if (image instanceof Blob) {
image = await codecs.imageDecode(image);
}
return image as NdArray<Uint8Array>;
}
function convertFloat32ToUint8(
float32Array: NdArray<Float32Array>
): NdArray<Uint8Array> {
const uint8Array = new Uint8Array(float32Array.data.length);
for (let i = 0; i < float32Array.data.length; i++) {
uint8Array[i] = float32Array.data[i] * 255;
}
return ndarray(uint8Array, float32Array.shape);
}
================================================
FILE: packages/node/tsconfig.json
================================================
{
"compilerOptions": {
"lib": ["DOM", "ES2015"],
"resolveJsonModule": true,
"esModuleInterop": true,
"emitDeclarationOnly": true,
"declaration": true,
"target": "ES6",
"moduleResolution": "Node16"
}
}
================================================
FILE: packages/node-e2e/fixtures/images/img2img.sh
================================================
filename="photo-1686002359940-6a51b0d64f68.jpeg"
basename="${filename%.*}"
cp "$filename" "$filename".orig
magick "$filename" "$basename".png
magick "$filename" "$basename".webp
magick "$filename" "$basename".jpg
magick "$filename" "$basename".avif
magick "$filename" "$basename".heif
# Raw RGB
magick "$filename" -depth 8 "$basename".rgb
magick "$filename" -depth 8 "$basename".cmyk
# rgb to tensor
magick "$filename" "$basename".pdf
magick "$filename" "$basename".psd
================================================
FILE: packages/node-e2e/package.json
================================================
{
"name": "e2e",
"private": true,
"scripts": {},
"devDependencies": {
"@imgly/background-removal-node": "workspace:*",
"jest": "^29.6.2"
},
"version": "1.7.0"
}
================================================
FILE: packages/node-e2e/src/example.test.js
================================================
// const pkg = require('@imgly/background-removal-node');
// const removeBackground = pkg.default;
// Test case to ensure the system doesn't crash with valid inputs
// test('removeBackground should not crash with valid inputs', async () => {
// const image = 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1024&q=80';
// const result = await removeBackground(image, { debug: true })
// await expect(result).resolves.toBeInstanceOf(Blob);
// });
================================================
FILE: packages/node-examples/package.json
================================================
{
"name": "examples-node-cli",
"private": true,
"main": "index.mjs",
"scripts": {
"start": "node src/example_001.cjs"
},
"dependencies": {
"@imgly/background-removal-node": "workspace:*",
"uuidv4": "^6.2.13"
},
"version": "1.7.0"
}
================================================
FILE: packages/node-examples/src/example_001.cjs
================================================
const {
removeBackground,
segmentForeground,
applySegmentationMask
} = require('@imgly/background-removal-node');
const fs = require('fs');
const uuidv4 = require('uuid').v4;
const images = [
// 'files/photo-1686002359940-6a51b0d64f68.jpeg',
'files/photo-1686002359940-hires.webp'
// 'files/photo-1590523278191-hires.webp'
// 'https://images.unsplash.com/photo-1686002359940-6a51b0d64f68?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&q=80'
// 'https://images.unsplash.com/photo-1590523278191-995cbcda646b?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9'
];
async function run() {
const randomImage = images[Math.floor(Math.random() * images.length)];
console.log('Random image: ' + randomImage);
const config = {
debug: false,
// publicPath: ...
progress: (key, current, total) => {
const [type, subtype] = key.split(':');
console.log(
`${type} ${subtype} ${((current / total) * 100).toFixed(0)}%`
);
},
// model: 'small',
model: 'isnet',
output: {
quality: 0.8,
format: 'image/webp' //image/jpeg, image/webp
}
};
console.time();
const blob = await removeBackground(randomImage, config);
// const mask = await segmentForeground(randomImage, config);
// const blob = await applySegmentationMask(randomImage, mask, config);
console.timeEnd();
const buffer = await blob.arrayBuffer();
try {
const format = config.output.format.split('/').pop();
const outFile = `tmp/${uuidv4()}.${format}`;
await fs.promises.mkdir('tmp', { recursive: true });
await fs.promises.writeFile(outFile, Buffer.from(buffer));
console.log(`Image saved to ${outFile}`);
} catch (error) {
console.error(error);
}
}
run();
================================================
FILE: packages/web/CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.5.6]
### Changed
- Upgrade onnx-runtime
## [1.5.0]
### Added
- Added option to execute on gpu (webgpu) and cpu. Enable by setting `device: "gpu"`
- Added isnet model for webgpu
## [1.4.5]
### Added
- Added ThirdPartyLicenses.json
## [1.4.0]
### Added
- Moved all data into it's own package. Therefore, reducing the main package size for the general case.
- Bumped onnx runtime to 1.17 Changed
- Changed license from GPL to AGPL Changed
- Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.
- Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.
### Changed
- Fallback to Canvas if OffscreenCanvas is not available
- Typescript bindings are generated with tsc
## [1.3.0]
### Added
- Resources are now chunked to 4MB for better caching performance and download restart.
- Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.
- Config option to export 'x-alpha8' format to get receive single channel alpha mask.
### Removed
- Configuration options to specify if background, foreground or mask is exported.
### Changed
- Changed the return value type of the progress callback from undefined to void
- Output is now in the original image size. Mask is upscaled and applied to the original image.
## [1.2.1]
### Added
- `CHANGELOG.md` for an better overview of the changes.
- support for raw `rgba8` export formats.
## [1.2.0]
### Added
- Support `foreground`, `background` and `mask` export type.
- Added support for `webp` and `jpeg` export formats.
================================================
FILE: packages/web/LICENSE.md
================================================
# GNU Affero General Public License
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. <<http://fsf.org/>>_
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
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.
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.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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
<<http://www.gnu.org/licenses/>>.
================================================
FILE: packages/web/README.md
================================================
# Background Removal in the Browser
We are always looking for great people at IMG.LY. If you are working with our background removal library you might be a perfect fit! **Apply now at [IMG.LY Careers](https://img.ly/company/careers/?utm_source=github&utm_medium=readme&utm_campaign=background-removal-js)**
<p align="center"> <img src="https://img.ly/showcases/cesdk/web/s/case-thumbnail/background-removal/background-removal-0.png?utm_source=github&utm_medium=project&utm_campaign=background-removal-js" alt="background removal js showcase" /> </p>
Remove backgrounds from images directly in the browser environment with ease and no additional costs or privacy concerns. Explore an [interactive demo](https://img.ly/showcases/cesdk/web/background-removal/web?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).
## News
For more detail information please refer to the [CHANGELOG](./CHANGELOG.md).
## Overview
`@imgly/background-removal` is a powerful npm package that allows developers to seamlessly remove the background from images directly in the browser. With its unique features and capabilities, this package offers an innovative and cost-effective solution for background removal tasks without compromising data privacy.
The key features of `@imgly/background-removal` are:
- **In-Browser Background Removal**: Our one-of-a-kind solution performs the entire background removal process directly in the user's browser, eliminating the need for additional server costs. By leveraging the computing power of the local device, users can enjoy a fast and efficient background removal process.
- **Data Protection**: As `@imgly/background-removal` runs entirely in the browser, users can have peace of mind knowing that their images and sensitive information remain secure within their own devices. With no data transfers to external servers, data privacy concerns are effectively mitigated.
- **Seamless Integration with IMG.LY's CE.SDK**: `@imgly/background-removal` provides seamless integration with [IMG.LY's CE.SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), allowing developers to easily incorporate powerful in-browser image matting and background removal capabilities into their projects.
The Neural Network ([ONNX model](https://onnx.ai/)) and WASM files used by `@imgly/background-removal` are hosted by [IMG.LY](https://img.ly/) by default. See the section Custom Asset Serving if you want to host them on your own servers.
## Installation
You can install `@imgly/background-removal` via npm or yarn. You also need to install the onnxruntime-web peer dependency. Use the following commands to install the packages:
### NPM
```shell
npm install @imgly/background-removal onnxruntime-web@1.21.0-dev.20250206-d981b153d3
```
## Usage
```typescript
import imglyRemoveBackground from "@imgly/background-removal"
let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;
imglyRemoveBackground(image_src).then((blob: Blob) => {
// The result is a blob encoded as PNG. It can be converted to an URL to be used as HTMLImage.src
const url = URL.createObjectURL(blob);
})
```
Note: On the first run the wasm and onnx model files are fetched. This might, depending on the bandwidth, take time. Therefore, the first run takes proportionally longer than each consecutive run. Also, all files are cached by the browser and an additional model cache.
## Advanced Configuration
The library does not need any configuration to get started. However, there are optional parameters that influence the behaviour and give more control over the library.
```typescript
type Config = {
publicPath: string; // The public path used for model and wasm files. Default: 'https://staticimgly.com/${PACKAGE_NAME}-data/${PACKAGE_VERSION}/dist/'
debug: bool; // enable or disable useful console.log outputs
device: 'cpu' | 'gpu'; // choose the execution device. gpu will use webgpu if available
model: 'isnet' | 'isnet_fp16' | 'isnet_quint8'; // The model to use. (Default "isnet_fp16")
output: {
format: 'image/png' | 'image/jpeg' | 'image/webp'; // The output format. (Default "image/png")
quality: number; // The quality. (Default: 0.8)
type: 'foreground' | 'background' | 'mask'; // The output type. (Default "foreground")
};
};
```
### NextJS
Note that currently only NextJS 15 is supported.
### Download Size vs Quality
The onnx model is shipped in various sizes and needs.
- small (\~40 MB) is the smallest model and is in most cases working fine but sometimes shows some artifacts. It's a quantized model.
- medium (\~80MB) is the default model.
### Preloading Assets
Per default, assets are downloaded on demand. You might enforce downloading all assets at once at any time by preloading them:
```typescript
import removeBackground, { preload, Config } from '@imgly/background-removal';
const config: Configuration = ...;
preload(config).then(() => {
console.log("Asset preloading succeeded")
})
```
### Download Progress Monitoring
On the first run, the necessary data will be fetched and stored in the browser cache. Since the download might take some time, you have the option to tap into the download progress.
```typescript
let config: Config = {
progress: (key, current, total) => {
console.log(`Downloading ${key}: ${current} of ${total}`);
}
};
```
### Performance
The performance is largely dependent on the feature set available. Most prominently, ensure that `SharedArrayBuffer` is available [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer). Due to the security requirements of `SharedArrayBuffer` two headers need to be set to cross-origin isolate your site:
```typescript
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp'
```
### Custom Asset Serving
The wasm and onnx neural networks are hosted by IMG.LY by default. For production use, we advise you to host them yourself:
- Download the following package with the package version that matches your `@imgly/background-removal` version from the IMG.LY CDN and decompress it. Note that you need to replace `YOUR_PACKAGE_VERSION` with the actual version of the package you are using. The URL is `https://staticimgly.com/@imgly/background-removal-data/YOUR_PACKAGE_VERSION/package.tgz`.
- Move the content of the `package/dist` folder to be served by your web server. This often is the `/public` folder.
```typescript
import imglyRemoveBackground, {Config} from "@imgly/background-removal"
const public_path = "https://example.com/assets/" ; // the path assets are served from
let config: Config = {
publicPath: public_path, // path to the wasm files
};
let image_src: ImageData | ArrayBuffer | Uint8Array | Blob | URL | string = ...;
imglyRemoveBackground(image_src, config).then((blob: Blob) => {
// result is a blob encoded as PNG.
// It can be converted to an URL to be used as HTMLImage.src
const url = URL.createObjectURL(blob);
})
```
### Debug Outputs
Enable debug outputs and logging to the console
```typescript
let config: Config = {
debug: true
};
```
### Cross-Origin Resource Sharing (CORS)
If you are running into CORS issues you might want to pass additional parameters to the fetch function via
```typescript
let config: Config = {
fetchArgs: {
mode: 'no-cors'
}
};
```
### Fetch Args
`fetchArgs` are passed as second parameters to the fetch function as described in [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
## Who is it for?
`@imgly/background-removal` is ideal for developers and projects that require efficient and cost-effective background removal directly in the browser. It caters to a wide range of use cases, including but not limited to:
- _E-commerce applications_ that need to remove backgrounds from product images in real time.
- _Image editing applications_ that require background removal capabilities for enhancing user experience.
- _Web-based graphic design tools_ that aim to simplify the creative process with in-browser background removal.
Whether you are a professional developer or a hobbyist, `@imgly/background-removal` empowers you to deliver impressive applications and services with ease.
## License
The software is free for use under the AGPL License. Please contact [support@img.ly](mailto:support@img.ly?subject=Background-Removal%20License) for questions about other licensing options.
## Authors & Contributors
This library is made by IMG.LY shipping the world's premier SDKs for building creative applications. Start your trial of the [CreativeEditor SDK](https://img.ly/products/creative-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js), [PhotoEditor SDK](https://img.ly/products/photo-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js) & [VideoEditor SDK](https://img.ly/products/video-sdk?utm_source=github&utm_medium=project&utm_campaign=background-removal-js).
================================================
FILE: packages/web/ThirdPartyLicenses.json
================================================
{
"onnxruntime-web": {
"source": "https://www.npmjs.com/package/onnxruntime-web",
"type": "code",
"license": "MIT"
},
"ISNET": {
"source": "https://github.com/xuebinqin/DIS",
"type": "model",
"license": "MIT"
},
"lodash-es": {
"source": "https://lodash.com/",
"type": "code",
"license": "MIT"
},
"ndarray": {
"source": "https://www.npmjs.com/package/ndarray",
"type": "code",
"license": "MIT"
},
"zod": {
"source": "https://www.npmjs.com/package/zod",
"type": "code",
"license": "MIT"
}
}
================================================
FILE: packages/web/changelog/1.2.0/20230811184244-export_type_and_formats.yml
================================================
---
type: Added
description: Support `foreground`, `background` and `mask` export type.
---
type: Added
description: Added support for `webp` and `jpeg` export formats.
================================================
FILE: packages/web/changelog/1.2.1/20230811184244-Changelog_item.yml
================================================
---
type: Added
description: |
`CHANGELOG.md` for an better overview of the changes.
---
type: Added
description: |
support for raw `rgba8` export formats.
================================================
FILE: packages/web/changelog/1.3.0/20230612112148-progress_return_type.yaml
================================================
---
type: Changed
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Changed the return value type of the progress callback from undefined to void
================================================
FILE: packages/web/changelog/1.3.0/20231512181521-resource_data_chunking.yaml
================================================
---
type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Resources are now chunked to 4MB for better caching performance and download restart.
================================================
FILE: packages/web/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml
================================================
---
type: Changed
# type: Removed
# type: Security
# private: true
description: |
Output is now in the original image size. Mask is upscaled and applied to the original image.
---
type: Added
# type: Removed
# type: Security
# private: true
description: |
Seperate functions for `removeBackground`, `removeForeground`, and `segmentForeground`. Later will extract the mask only.
---
type: Removed
# type: Removed
# type: Security
# private: true
description: |
Configuration options to specify if background, foreground or mask is exported.
---
type: Added
# type: Removed
# type: Security
# private: true
description: |
Config option to export 'x-alpha8' format to get receive single channel alpha mask.
================================================
FILE: packages/web/changelog/1.4.0/20233012103509-Moved.yaml
================================================
---
type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Moved all data into it's own package. Therefore, reducing the main package size for the general case.
================================================
FILE: packages/web/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Bumped onnx runtime to 1.17 Changed
================================================
FILE: packages/web/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Changed license from GPL to AGPL Changed
================================================
FILE: packages/web/changelog/1.4.0/20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.
================================================
FILE: packages/web/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added option to apply segmentation mask to any image. Used for applying the same mask to srcsets.
================================================
FILE: packages/web/changelog/1.4.0/20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml
================================================
---
type: Changed
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Fallback to Canvas if OffscreenCanvas is not available
================================================
FILE: packages/web/changelog/1.4.0/20242301155639-Typescript_bindings_are_generated_with_tsc.yaml
================================================
---
type: Changed
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Typescript bindings are generated with tsc
================================================
FILE: packages/web/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added ThirdPartyLicenses.json
================================================
FILE: packages/web/changelog/1.5.0/20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added option to execute on gpu (webgpu) and cpu. Enable by setting `device: "gpu"`
================================================
FILE: packages/web/changelog/1.5.0/20242503170808-Added_isnet_model_for_webgpu_Added.yaml
================================================
---
type: Added
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Added isnet model for webgpu
================================================
FILE: packages/web/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
================================================
---
type: Changed
# type: Added
# type: Changed
# type: Removed
# type: Security
# private: true
description: |
Upgrade onnx-runtime
================================================
FILE: packages/web/changelog/Unreleased/.keep
================================================
================================================
FILE: packages/web/changelog/info.yml
================================================
---
description: |
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
================================================
FILE: packages/web/package.json
================================================
{
"name": "@imgly/background-removal",
"version": "1.7.0",
"description": "Background Removal in the Browser",
"keywords": [
"background-removal",
"client-side",
"data-privacy",
"image-segmentation",
"image-matting",
"onnx"
],
"repository": {
"type": "git",
"url": "git+https://github.com/imgly/background-removal-js.git"
},
"license": "SEE LICENSE IN LICENSE.md",
"author": {
"name": "IMG.LY GmbH",
"email": "support@img.ly",
"url": "https://img.ly"
},
"bugs": {
"email": "support@img.ly"
},
"source": "./src/index.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/src/index.d.ts",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.mjs",
"types": "./dist/src/index.d.ts"
}
},
"homepage": "https://img.ly/showcases/cesdk/web/background-removal",
"files": [
"LICENSE.md",
"README.md",
"CHANGELOG.md",
"ThirdPartyLicenses.json",
"dist/",
"bin/"
],
"scripts": {
"start": "pnpm run watch",
"clean": "npx rimraf dist",
"test": "true",
"resources": "node ../../scripts/package-resources.mjs",
"changelog:create": "node ../../scripts/changelog/changelog-create.mjs",
"changelog:generate": "node ../../scripts/changelog/changelog-generate.mjs",
"build": "pnpm run clean && pnpm run types && pnpm run resources && pnpm run changelog:generate && node scripts/build.mjs",
"types": " npx tsc --declaration --emitDeclarationOnly --declarationDir dist --declarationMap",
"watch": "pnpm run clean && pnpm run resources && pnpm run changelog:generate && node scripts/watch.mjs",
"publish:latest": "pnpm publish --tag latest --access public",
"publish:next": "pnpm publish --tag next --access public",
"package:pack": "pnpm pack . --pack-destination ../../releases",
"check:all": "pnpm run check:pretty",
"check:pretty": "prettier --list-different './src/**/*.{ts,tsx}'",
"pretty": "prettier --write './src/**/*.{ts,tsx}'"
},
"dependencies": {
"lodash-es": "^4.17.21",
"ndarray": "~1.0.0",
"zod": "^3.23.8"
},
"peerDependencies": {
"onnxruntime-web": "1.21.0"
},
"devDependencies": {
"@types/lodash-es": "^4.17.12",
"@types/ndarray": "~1.0.14",
"@types/node": "~20.3.0",
"assert": "~2.0.0",
"esbuild": "~0.18.0",
"glob": "~10.3.0",
"npm-dts": "~1.3.0",
"process": "~0.11.0",
"ts-loader": "~9.4.0",
"tslib": "~2.5.0",
"typescript": "~5.1.0",
"util": "~0.12.0",
"webpack": "~5.85.0",
"webpack-cli": "~5.1.0"
}
}
================================================
FILE: packages/web/scripts/build.mjs
================================================
export { configs };
import * as esbuild from 'esbuild';
import { readFileSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(
readFileSync(path.resolve(__dirname, '../package.json'))
);
const dependencies = [Object.keys(pkg.peerDependencies)].flat();
const configs = [
{
entryPoints: ['src/index.ts'],
bundle: true,
sourcemap: true,
platform: 'browser',
external: dependencies,
format: 'cjs',
outfile: 'dist/index.cjs'
},
{
entryPoints: ['src/index.ts'],
bundle: true,
sourcemap: true,
external: dependencies,
platform: 'browser',
format: 'esm',
outfile: 'dist/index.mjs'
}
];
await configs.map(async (config) => await esbuild.build(config));
================================================
FILE: packages/web/scripts/watch.mjs
================================================
import * as esbuild from 'esbuild';
import { configs } from './build.mjs';
import dts from 'npm-dts';
new dts.Generator({
entry: 'src/index.ts',
output: 'dist/index.d.ts'
}).generate();
const contexts = await Promise.all(
configs.map((config) => esbuild.context(config))
);
await Promise.any(contexts.map((ctx) => ctx.watch()));
console.log('watching...');
================================================
FILE: packages/web/src/MimeType.ts
================================================
export class MimeType {
type: string = 'application/octet-stream';
params: Record<string, string> = {};
private constructor(type: string, params: Record<string, string>) {
this.type = type;
this.params = params;
}
toString(): string {
const paramsStr = [];
for (const key in this.params) {
const value = this.params[key];
paramsStr.push(`${key}=${value}`);
}
return [this.type, ...paramsStr].join(';');
}
static create(type, params: Record<string, string>): MimeType {
return new MimeType(type, params);
}
isIdentical(other: MimeType): Boolean {
return this.type === other.type && this.params === other.params;
}
isEqual(other: MimeType): Boolean {
return this.type === other.type;
}
static fromString(mimeType: string): MimeType {
const [type, ...paramsArr] = mimeType.split(';');
const params: Record<string, string> = {};
for (const param of paramsArr) {
const [key, value] = param.split('=');
params[key.trim()] = value.trim();
}
return new MimeType(type, params);
}
}
================================================
FILE: packages/web/src/api/v1.ts
================================================
export default removeBackground;
export {
preload,
removeBackground,
removeForeground,
alphamask,
segmentForeground,
applySegmentationMask
};
export type { Config, ImageSource };
import memoize from 'lodash-es/memoize';
import { initInference, runInference } from '../inference';
import { Config, validateConfig } from '../schema';
import * as utils from '../utils';
import { ImageSource } from '../utils';
const init = memoize(initInference, (config) => JSON.stringify(config));
async function preload(configuration?: Config): Promise<void> {
await init(configuration);
return;
}
/**
* Removes the background from an image.
*
* @param image - The image to remove the background from.
* @param configuration - Optional configuration for the background removal process.
* @returns A Promise that resolves to the resulting image with the background removed.
*/
async function removeBackground(
image: ImageSource,
configuration?: Config
): Promise<Blob> {
const { config, session } = await init(configuration);
if (config.progress) config.progress('compute:decode', 0, 4);
const inputImageTensor = await utils.imageSourceToImageData(image, config);
config.progress?.('compute:inference', 1, 4);
const [alphamask, imageTensor] = await runInference(
inputImageTensor,
config,
session
);
config.progress?.('compute:mask', 2, 4);
const outImageTensor = imageTensor;
const [width, height] = outImageTensor.shape;
const stride = width * height;
for (let i = 0; i < stride; i += 1) {
outImageTensor.data[4 * i + 3] = alphamask.data[i];
}
config.progress?.('compute:encode', 3, 4);
const outImage = await utils.imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
config.progress?.('compute:encode', 4, 4);
return outImage;
}
/**
* Removes the foreground from an image.
*
* @param image - The image to remove the foreground from.
* @param configuration - Optional configuration for the foreground removal process.
* @returns A Promise that resolves to the resulting image with the foreground removed.
*/
async function removeForeground(
image: ImageSource,
configuration?: Config
): Promise<Blob> {
const { config, session } = await init(configuration);
const imageTensor = await utils.imageSourceToImageData(image, config);
const [alphamask, imageInput] = await runInference(
imageTensor,
config,
session
);
const outImageTensor = imageInput;
const [width, height, channels] = outImageTensor.shape;
const stride = width * height;
for (let i = 0; i < stride; i += 1) {
outImageTensor.data[4 * i + 3] = 255 - alphamask.data[i];
}
const outImage = await utils.imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
/**
* Segments the foreground of an image using a given configuration.
*
* @param image - The image source to segment.
* @param configuration - The optional configuration for the segmentation.
* @returns A Promise that resolves to the segmented foreground as a Blob.
*/
const alphamask = segmentForeground;
async function segmentForeground(
image: ImageSource,
configuration?: Config
): Promise<Blob> {
const { config, session } = await init(configuration);
const imageTensor = await utils.imageSourceToImageData(image, config);
let [height, width, channels] = imageTensor.shape;
const [alphamask, imageInput] = await runInference(
imageTensor,
config,
session
);
const stride = width * height;
const outImageTensor = imageTensor;
for (let i = 0; i < stride; i += 1) {
const index = 4 * i;
let alpha = alphamask.data[i];
outImageTensor.data[index] = 255;
outImageTensor.data[index + 1] = 255;
outImageTensor.data[index + 2] = 255;
outImageTensor.data[index + 3] = alpha;
}
const outImage = await utils.imageEncode(
outImageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
async function applySegmentationMask(
image,
mask,
config?: Config
): Promise<Blob> {
config = validateConfig(config);
const imageTensor = await utils.imageSourceToImageData(image, config);
const [imageHeight, imageWidth, imageChannels] = imageTensor.shape;
const maskTensor = await utils.imageSourceToImageData(mask, config);
const [maskHeight, maskWidth, maskChannels] = maskTensor.shape;
const alphaMask =
maskHeight !== imageHeight || maskWidth !== imageWidth
? utils.tensorResizeBilinear(maskTensor, imageWidth, imageHeight)
: maskTensor;
const stride = imageWidth * imageHeight;
for (let i = 0; i < stride; i += 1) {
const idxImage = imageChannels * i;
const idxMask = maskChannels * i;
imageTensor.data[idxImage + 3] = alphaMask.data[idxMask + 3];
}
const outImage = await utils.imageEncode(
imageTensor,
config.output.quality,
config.output.format
);
return outImage;
}
================================================
FILE: packages/web/src/capabilities.js
================================================
export const bigInt = () =>
(async (e) => {
try {
return (
(await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0)) ===
BigInt(0)
);
} catch (e) {
return !1;
}
})(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 1, 126, 1, 126, 3, 2, 1, 0, 7,
5, 1, 1, 98, 0, 0, 10, 6, 1, 4, 0, 32, 0, 11
])
),
bulkMemory = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 3, 1, 0,
1, 10, 14, 1, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11
])
),
exceptions = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6,
0, 6, 64, 25, 11, 11
])
),
extendedConst = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 0, 1, 11, 9, 1, 0, 65, 1, 65, 2,
106, 11, 0
])
),
gc = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 10, 2, 95, 1, 125, 0, 96, 0, 1, 107, 0,
3, 2, 1, 1, 10, 12, 1, 10, 0, 67, 0, 0, 0, 0, 251, 7, 0, 11
])
),
memory64 = () =>
WebAssembly.validate(
new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 4, 1])
),
multiValue = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 0, 2, 127, 127, 3, 2, 1, 0,
10, 8, 1, 6, 0, 65, 0, 65, 0, 11
])
),
mutableGlobals = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 2, 8, 1, 1, 97, 1, 98, 3, 127, 1, 6, 6, 1,
127, 1, 65, 0, 11, 7, 5, 1, 1, 97, 3, 1
])
),
referenceTypes = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 7, 1, 5,
0, 208, 112, 26, 11
])
),
relaxedSimd = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 15,
1, 13, 0, 65, 1, 253, 15, 65, 2, 253, 15, 253, 128, 2, 11
])
),
saturatedFloatToInt = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 12, 1,
10, 0, 67, 0, 0, 0, 0, 252, 0, 26, 11
])
),
signExtensions = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6,
0, 65, 0, 192, 26, 11
])
),
simd = () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10,
1, 8, 0, 65, 0, 253, 15, 253, 98, 11
])
),
streamingCompilation = () =>
(async () => 'compileStreaming' in WebAssembly)(),
tailCall = async () =>
WebAssembly.validate(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4,
0, 18, 0, 11
])
),
threads = () =>
(async (e) => {
try {
return (
'undefined' != typeof MessageChannel &&
new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),
WebAssembly.validate(e)
);
} catch (e) {
return !1;
}
})(
new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3,
1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11
])
);
export const webgpu = async () => {
if (navigator.gpu === undefined) return false;
const adapter = await navigator.gpu.requestAdapter();
return adapter !== null;
};
export const maxNumThreads = () => navigator.hardwareConcurrency ?? 4;
================================================
FILE: packages/web/src/codecs.ts
================================================
export { imageEncode, imageDecode, MimeType };
import { MimeType } from './MimeType';
import { imageBitmapToImageData, createCanvas } from './utils';
import ndarray, { NdArray } from 'ndarray';
async function imageDecode(blob: Blob): Promise<NdArray<Uint8Array>> {
const mime = MimeType.fromString(blob.type);
switch (mime.type) {
case 'image/x-alpha8': {
const width = parseInt(mime.params['width']);
const height = parseInt(mime.params['height']);
return ndarray(new Uint8Array(await blob.arrayBuffer()), [
height,
width,
1
]);
}
case 'image/x-rgba8': {
const width = parseInt(mime.params['width']);
const height = parseInt(mime.params['height']);
return ndarray(new Uint8Array(await blob.arrayBuffer()), [
height,
width,
4
]);
}
case 'application/octet-stream': // this is an unknwon type
case `image/png`:
case `image/jpeg`:
case `image/jpg`:
case `image/webp`: {
const imageBitmap = await createImageBitmap(blob);
const imageData = imageBitmapToImageData(imageBitmap);
return ndarray(new Uint8Array(imageData.data), [
imageData.height,
imageData.width,
4
]);
}
default:
throw new Error(
`Invalid format: ${mime.type} with params: ${mime.params}`
);
}
}
async function imageEncode(
imageTensor: NdArray<Uint8Array>,
quality: number = 0.8,
format: string = 'image/png'
): Promise<Blob> {
const [height, width, channels] = imageTensor.shape;
switch (format) {
case 'image/x-alpha8':
case 'image/x-rgba8': {
const mime = MimeType.create(format, {
width: width.toString(),
height: height.toString()
});
return new Blob([imageTensor.data], { type: mime.toString() });
}
case `image/png`:
case `image/jpeg`:
case `image/webp`: {
const imageData = new ImageData(
new Uint8ClampedArray(imageTensor.data),
width,
height
);
var canvas = createCanvas(imageData.width, imageData.height);
var ctx = canvas.getContext('2d')!;
ctx.putImageData(imageData, 0, 0);
return canvas.convertToBlob({ quality, type: format });
}
default:
throw new Error(`Invalid format: ${format}`);
}
}
================================================
FILE: packages/web/src/index.ts
================================================
export * from './api/v1';
// export * as next from './api/v2';
================================================
FILE: packages/web/src/inference.ts
================================================
export { initInference, runInference };
import { tensorResizeBilinear, tensorHWCtoBCHW } from './utils';
import { createOnnxSession, runOnnxSession } from './onnx';
import { Config, validateConfig } from './schema';
import { loadAsBlob } from './resource';
import ndarray, { NdArray } from 'ndarray';
import { convertFloat32ToUint8 } from './utils';
async function initBase(config: Config): Promise<unknown> {
if (config.debug) console.debug('Loading model...', config.model);
const model = config.model;
const blob = await loadAsBlob(`/models/${model}`, config);
const arrayBuffer = await blob.arrayBuffer();
const session = await createOnnxSession(arrayBuffer, config);
return session;
}
async function initInference(
config?: Config
): Promise<{ config: Config; session: { base: unknown } }> {
config = validateConfig(config);
const base = await initBase(config);
return { config, session: { base } };
}
async function runInference(
imageTensor: NdArray<Uint8Array>,
config: Config,
session: { base: unknown }
): Promise<[NdArray<Uint8Array>, NdArray<Uint8Array>]> {
const resolution = 1024;
const [srcHeight, srcWidth, srcChannels] = imageTensor.shape;
const keepAspect = false;
let resizedImageTensor = tensorResizeBilinear(
imageTensor,
resolution,
resolution,
keepAspect
);
const inputTensor = tensorHWCtoBCHW(resizedImageTensor); // this converts also from float to rgba
let predictionsDict = await runOnnxSession(
session.base,
[['input', inputTensor]],
['output'],
config
);
let alphamask = ndarray(predictionsDict[0].data, [resolution, resolution, 1]);
let alphamaskU8 = convertFloat32ToUint8(alphamask);
if (config.rescale) {
alphamaskU8 = tensorResizeBilinear(
alphamaskU8,
srcWidth,
srcHeight,
keepAspect
);
return [alphamaskU8, imageTensor];
} else {
return [alphamaskU8, resizedImageTensor];
}
}
================================================
FILE: packages/web/src/onnx.ts
================================================
export { createOnnxSession, runOnnxSession };
import ndarray, { NdArray } from 'ndarray';
import { InferenceSession, Tensor } from 'onnxruntime-web';
import * as caps from './capabilities';
import { loadAsUrl } from './resource';
import { Config } from './schema';
type ORT = typeof import('onnxruntime-web');
// use a dynamic import to avoid bundling the entire onnxruntime-web package
let ort: ORT | null = null;
const getOrt = async (useWebGPU: boolean): Promise<ORT> => {
if (ort !== null) {
return ort;
}
if (useWebGPU) {
ort = (await import('onnxruntime-web/webgpu')).default;
} else {
ort = (await import('onnxruntime-web')).default;
}
return ort;
};
async function createOnnxSession(model: any, config: Config) {
const useWebGPU = config.device === 'gpu' && (await caps.webgpu());
// BUG: proxyToWorker is not working for WASM/CPU Backend for now
const proxyToWorker = useWebGPU && config.proxyToWorker;
const executionProviders = [useWebGPU ? 'webgpu' : 'wasm'];
const ort = await getOrt(useWebGPU);
if (config.debug) {
console.debug('\tUsing WebGPU:', useWebGPU);
console.debug('\tProxy to Worker:', proxyToWorker);
ort.env.debug = true;
ort.env.logLevel = 'verbose';
}
ort.env.wasm.numThreads = caps.maxNumThreads();
ort.env.wasm.proxy = proxyToWorker;
// The path inside the resource bundle
const baseFilePath = useWebGPU
? '/onnxruntime-web/ort-wasm-simd-threaded.jsep'
: '/onnxruntime-web/ort-wasm-simd-threaded';
const wasmPath = await loadAsUrl(`${baseFilePath}.wasm`, config);
const mjsPath = await loadAsUrl(`${baseFilePath}.mjs`, config);
ort.env.wasm.wasmPaths = {
mjs: mjsPath,
wasm: wasmPath
};
if (config.debug) {
console.debug('ort.env.wasm:', ort.env.wasm);
}
const ortConfig: InferenceSession.SessionOptions = {
executionProviders: executionProviders,
graphOptimizationLevel: 'all',
executionMode: 'parallel',
enableCpuMemArena: true
};
const session = await ort.InferenceSession.create(model, ortConfig).catch(
(e: any) => {
throw new Error(
`Failed to create session: "${e}". Please check if the publicPath is set correctly.`
);
}
);
return session;
}
async function runOnnxSession(
session: any,
inputs: [string, NdArray<Float32Array>][],
outputs: [string],
config: Config
) {
const useWebGPU = config.device === 'gpu' && (await caps.webgpu());
const ort = await getOrt(useWebGPU);
const feeds: Record<string, any> = {};
for (const [key, tensor] of inputs) {
feeds[key] = new ort.Tensor(
'float32',
new Float32Array(tensor.data),
tensor.shape
);
}
const outputData = await session.run(feeds, {});
const outputKVPairs: NdArray<Float32Array>[] = [];
for (const key of outputs) {
const output: Tensor = outputData[key];
const shape: number[] = output.dims as number[];
const data: Float32Array = output.data as Float32Array;
const tensor = ndarray(data, shape);
outputKVPairs.push(tensor);
}
return outputKVPairs;
}
================================================
FILE: packages/web/src/resource.ts
================================================
export { loadAsBlob, loadAsUrl, loadAsArrayBuffer, preload, resolveChunkUrls };
import { Config } from './schema';
async function preload(config: Config): Promise<void> {
// load resource metadata
const resourceUrl = new URL('resources.json', config.publicPath);
const resourceResponse = await fetch(resourceUrl);
if (!resourceResponse.ok) {
throw new Error(
`Resource metadata not found. Ensure that the config.publicPath is configured correctly: ${config.publicPath}`
);
}
const resourceMap = await resourceResponse.json();
const keys = Object.keys(resourceMap);
await Promise.all(
keys.map(async (key) => {
return loadAsBlob(key, config);
})
);
}
async function loadAsUrl(url: string, config: Config): Promise<string> {
return URL.createObjectURL(await loadAsBlob(url, config));
}
async function loadAsArrayBuffer(
url: string,
config: Config
): Promise<ArrayBuffer> {
return await (await loadAsBlob(url, config)).arrayBuffer();
}
async function loadAsBlob(key: string, config: Config) {
// load resource metadata
const resourceUrl = new URL('resources.json', config.publicPath);
const resourceResponse = await fetch(resourceUrl);
if (!resourceResponse.ok) {
throw new Error(
`Resource metadata not found. Ensure that the config.publicPath is configured correctly.`
);
}
cons
gitextract_zf76w0ij/
├── .gitattributes
├── .github/
│ └── workflows/
│ └── pnpm-pr-check.yml
├── .gitignore
├── .husky/
│ └── pre-commit
├── .npmrc
├── .nvmrc
├── .prettierignore
├── .prettierrc.js
├── LICENSE.md
├── README.md
├── TODOS.md
├── bundle/
│ └── models/
│ ├── isnet
│ ├── isnet_fp16
│ └── isnet_quint8
├── package.json
├── packages/
│ ├── node/
│ │ ├── .resources.mjs
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE.md
│ │ ├── README.md
│ │ ├── ThirdPartyLicenses.json
│ │ ├── changelog/
│ │ │ ├── 1.2.0/
│ │ │ │ └── 20230811184244-export_type_and_formats.yml
│ │ │ ├── 1.2.1/
│ │ │ │ └── 20230811184244-Changelog_item.yml
│ │ │ ├── 1.3.0/
│ │ │ │ ├── 20230612112304-progress_return_type.yaml
│ │ │ │ ├── 20231512181521-resource_data_chunking.yaml
│ │ │ │ └── 20231512193816-upscale_mask_to_original_image.yaml
│ │ │ ├── 1.4.0/
│ │ │ │ ├── 20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml
│ │ │ │ ├── 20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml
│ │ │ │ ├── 20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
│ │ │ │ └── 20242301155647-Typescript_bindings_are_generated_with_tsc.yaml
│ │ │ ├── 1.4.5/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ ├── Unreleased/
│ │ │ │ └── .keep
│ │ │ └── info.yml
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ ├── build.mjs
│ │ │ └── watch.mjs
│ │ ├── src/
│ │ │ ├── codecs.ts
│ │ │ ├── index.ts
│ │ │ ├── inference.ts
│ │ │ ├── onnx.ts
│ │ │ ├── resource.ts
│ │ │ ├── schema.ts
│ │ │ ├── url.ts
│ │ │ └── utils.ts
│ │ └── tsconfig.json
│ ├── node-e2e/
│ │ ├── fixtures/
│ │ │ └── images/
│ │ │ └── img2img.sh
│ │ ├── package.json
│ │ └── src/
│ │ └── example.test.js
│ ├── node-examples/
│ │ ├── package.json
│ │ └── src/
│ │ └── example_001.cjs
│ ├── web/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE.md
│ │ ├── README.md
│ │ ├── ThirdPartyLicenses.json
│ │ ├── changelog/
│ │ │ ├── 1.2.0/
│ │ │ │ └── 20230811184244-export_type_and_formats.yml
│ │ │ ├── 1.2.1/
│ │ │ │ └── 20230811184244-Changelog_item.yml
│ │ │ ├── 1.3.0/
│ │ │ │ ├── 20230612112148-progress_return_type.yaml
│ │ │ │ ├── 20231512181521-resource_data_chunking.yaml
│ │ │ │ └── 20231512193816-upscale_mask_to_original_image.yaml
│ │ │ ├── 1.4.0/
│ │ │ │ ├── 20233012103509-Moved.yaml
│ │ │ │ ├── 20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml
│ │ │ │ ├── 20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml
│ │ │ │ ├── 20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
│ │ │ │ ├── 20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml
│ │ │ │ ├── 20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml
│ │ │ │ └── 20242301155639-Typescript_bindings_are_generated_with_tsc.yaml
│ │ │ ├── 1.4.5/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ ├── 1.5.0/
│ │ │ │ ├── 20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml
│ │ │ │ └── 20242503170808-Added_isnet_model_for_webgpu_Added.yaml
│ │ │ ├── 1.5.6/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ ├── Unreleased/
│ │ │ │ └── .keep
│ │ │ └── info.yml
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ ├── build.mjs
│ │ │ └── watch.mjs
│ │ ├── src/
│ │ │ ├── MimeType.ts
│ │ │ ├── api/
│ │ │ │ └── v1.ts
│ │ │ ├── capabilities.js
│ │ │ ├── codecs.ts
│ │ │ ├── index.ts
│ │ │ ├── inference.ts
│ │ │ ├── onnx.ts
│ │ │ ├── resource.ts
│ │ │ ├── schema.ts
│ │ │ ├── types.d.ts
│ │ │ ├── url.ts
│ │ │ └── utils.ts
│ │ └── tsconfig.json
│ ├── web-data/
│ │ ├── .resources.mjs
│ │ ├── LICENSE.md
│ │ ├── ThirdPartyLicenses.json
│ │ ├── changelog/
│ │ │ ├── 1.4.5/
│ │ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ │ └── 1.5.6/
│ │ │ └── 20242602190400-Added_ThirdPartyLicenses_json_Added.yaml
│ │ └── package.json
│ └── web-examples/
│ ├── next-example/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── eslint.config.mjs
│ │ ├── next.config.ts
│ │ ├── package.json
│ │ ├── src/
│ │ │ └── app/
│ │ │ ├── BackgroundRemoval.tsx
│ │ │ ├── BackgroundRemovalNoSSR.tsx
│ │ │ ├── globals.css
│ │ │ ├── layout.tsx
│ │ │ └── page.tsx
│ │ └── tsconfig.json
│ └── vite-project/
│ ├── .gitignore
│ ├── .vercel/
│ │ ├── README.txt
│ │ └── project.json
│ ├── README.md
│ ├── index.html
│ ├── package.json
│ ├── src/
│ │ ├── App.vue
│ │ ├── main.ts
│ │ ├── style.css
│ │ └── vite-env.d.ts
│ ├── tsconfig.json
│ ├── tsconfig.node.json
│ └── vite.config.ts
├── pnpm-workspace.yaml
└── scripts/
├── changelog/
│ ├── changelog-create.mjs
│ ├── changelog-generate.mjs
│ └── template.yml.ejs
├── deploy-assets.mjs
├── package-resources.mjs
└── package-version.mjs
SYMBOL INDEX (94 symbols across 26 files)
FILE: packages/node-examples/src/example_001.cjs
function run (line 17) | async function run() {
FILE: packages/node/src/codecs.ts
function imageDecode (line 6) | async function imageDecode(blob: Blob): Promise<NdArray<Uint8Array>> {
function imageEncode (line 54) | async function imageEncode(
class MimeType (line 86) | class MimeType {
method constructor (line 90) | private constructor(type: string, params: Record<string, string>) {
method toString (line 95) | toString(): string {
method create (line 104) | static create(type, params: Record<string, string>): MimeType {
method isIdentical (line 108) | isIdentical(other: MimeType): Boolean {
method isEqual (line 112) | isEqual(other: MimeType): Boolean {
method fromString (line 116) | static fromString(mimeType: string): MimeType {
FILE: packages/node/src/index.ts
function removeBackground (line 27) | async function removeBackground(
function removeForeground (line 60) | async function removeForeground(
function segmentForeground (line 92) | async function segmentForeground(
function applySegmentationMask (line 135) | async function applySegmentationMask(
FILE: packages/node/src/inference.ts
function initInference (line 11) | async function initInference(config?: Config) {
function runInference (line 22) | async function runInference(
FILE: packages/node/src/onnx.ts
function createOnnxSession (line 8) | async function createOnnxSession(model: any, config: Config) {
function runOnnxSession (line 30) | async function runOnnxSession(
FILE: packages/node/src/resource.ts
function loadAsUrl (line 8) | async function loadAsUrl(url: string, config: Config) {
function loadFromURI (line 12) | async function loadFromURI(
function loadAsBlob (line 30) | async function loadAsBlob(key: string, config: Config) {
FILE: packages/node/src/schema.ts
function isURI (line 6) | function isURI(s: string) {
type Config (line 93) | type Config = z.infer<typeof ConfigSchema>;
function validateConfig (line 95) | function validateConfig(configuration?: Config): Config {
FILE: packages/node/src/url.ts
function isAbsoluteURI (line 3) | function isAbsoluteURI(url: string): boolean {
function ensureAbsoluteURI (line 8) | function ensureAbsoluteURI(url: string, baseUrl: string): URL {
FILE: packages/node/src/utils.ts
type ImageSource (line 20) | type ImageSource =
function tensorResizeBilinear (line 28) | function tensorResizeBilinear(
function tensorHWCtoBCHW (line 77) | function tensorHWCtoBCHW(
function calculateProportionalSize (line 98) | function calculateProportionalSize(
function imageSourceToImageData (line 112) | async function imageSourceToImageData(
function convertFloat32ToUint8 (line 132) | function convertFloat32ToUint8(
FILE: packages/web-examples/next-example/src/app/layout.tsx
function RootLayout (line 9) | function RootLayout({
FILE: packages/web-examples/next-example/src/app/page.tsx
function Home (line 3) | function Home() {
FILE: packages/web/src/MimeType.ts
class MimeType (line 1) | class MimeType {
method constructor (line 5) | private constructor(type: string, params: Record<string, string>) {
method toString (line 10) | toString(): string {
method create (line 19) | static create(type, params: Record<string, string>): MimeType {
method isIdentical (line 23) | isIdentical(other: MimeType): Boolean {
method isEqual (line 27) | isEqual(other: MimeType): Boolean {
method fromString (line 31) | static fromString(mimeType: string): MimeType {
FILE: packages/web/src/api/v1.ts
function preload (line 21) | async function preload(configuration?: Config): Promise<void> {
function removeBackground (line 33) | async function removeBackground(
function removeForeground (line 75) | async function removeForeground(
function segmentForeground (line 113) | async function segmentForeground(
function applySegmentationMask (line 149) | async function applySegmentationMask(
FILE: packages/web/src/codecs.ts
function imageDecode (line 6) | async function imageDecode(blob: Blob): Promise<NdArray<Uint8Array>> {
function imageEncode (line 48) | async function imageEncode(
FILE: packages/web/src/inference.ts
function initBase (line 11) | async function initBase(config: Config): Promise<unknown> {
function initInference (line 20) | async function initInference(
function runInference (line 28) | async function runInference(
FILE: packages/web/src/onnx.ts
type ORT (line 9) | type ORT = typeof import('onnxruntime-web');
function createOnnxSession (line 24) | async function createOnnxSession(model: any, config: Config) {
function runOnnxSession (line 76) | async function runOnnxSession(
FILE: packages/web/src/resource.ts
function preload (line 5) | async function preload(config: Config): Promise<void> {
function loadAsUrl (line 24) | async function loadAsUrl(url: string, config: Config): Promise<string> {
function loadAsArrayBuffer (line 27) | async function loadAsArrayBuffer(
function loadAsBlob (line 34) | async function loadAsBlob(key: string, config: Config) {
function resolveChunkUrls (line 89) | async function resolveChunkUrls(key: string, config: Config) {
FILE: packages/web/src/schema.ts
type Config (line 100) | type Config = z.infer<typeof ConfigSchema>;
function validateConfig (line 102) | function validateConfig(configuration?: Config): Config {
FILE: packages/web/src/types.d.ts
type Navigator (line 1) | interface Navigator {
FILE: packages/web/src/url.ts
function isAbsoluteURI (line 3) | function isAbsoluteURI(url: string): boolean {
function ensureAbsoluteURI (line 11) | function ensureAbsoluteURI(url: string, baseUrl: string): string {
FILE: packages/web/src/utils.ts
type ImageSource (line 17) | type ImageSource =
function imageBitmapToImageData (line 26) | function imageBitmapToImageData(imageBitmap: ImageBitmap): ImageData {
function createTypeArray (line 33) | function createTypeArray<T extends TypedArray>(length: number) {
function tensorResizeBilinear (line 50) | function tensorResizeBilinear<T extends TypedArray>(
function tensorHWCtoBCHW (line 107) | function tensorHWCtoBCHW(
function imageSourceToImageData (line 128) | async function imageSourceToImageData(
function convertFloat32ToUint8 (line 149) | function convertFloat32ToUint8(
function createCanvas (line 159) | function createCanvas(width, height) {
FILE: scripts/changelog/changelog-create.mjs
function parseStringToArgs (line 58) | function parseStringToArgs(str) {
function parseExample (line 62) | function parseExample(prompt) {
function parsePrompt (line 70) | function parsePrompt(prompt, flags) {
function main (line 150) | function main(argv) {
FILE: scripts/changelog/changelog-generate.mjs
function parseChangelogItems (line 49) | function parseChangelogItems(entries) {
FILE: scripts/deploy-assets.mjs
function syncToS3 (line 16) | async function syncToS3() {
FILE: scripts/package-resources.mjs
function calculateSHA256 (line 15) | async function calculateSHA256(filePath) {
function copyFile (line 26) | async function copyFile(sourcePath, destinationPath) {
function linkFile (line 38) | async function linkFile(sourcePath, destinationPath) {
function deleteFile (line 50) | async function deleteFile(filePath) {
function isFileHidden (line 69) | function isFileHidden(filePath) {
function listAllFiles (line 74) | async function listAllFiles(dir) {
function fileExists (line 100) | function fileExists(filePath) {
function sizeFile (line 104) | async function sizeFile(filePath) {
function isFunction (line 116) | function isFunction(variable) {
function transform (line 120) | async function transform(fileName, entry) {
function loadConfig (line 153) | async function loadConfig() {
function main (line 162) | async function main() {
function generateFiles (line 169) | async function generateFiles() {
function loadResourceMetadata (line 186) | async function loadResourceMetadata() {
function saveResourceMetadata (line 193) | async function saveResourceMetadata(filesToProcess) {
FILE: scripts/package-version.mjs
function getFiles (line 8) | function getFiles(dir) {
Condensed preview — 124 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (293K chars).
[
{
"path": ".gitattributes",
"chars": 772,
"preview": "bundle/**/* filter=lfs diff=lfs merge=binary\n**/*.onnx filter=lfs diff=lfs merge=binary\n**/*.ort filter=lfs diff=lfs mer"
},
{
"path": ".github/workflows/pnpm-pr-check.yml",
"chars": 250,
"preview": "name: Build and test pnpm workspace\n\non:\n push:\n branches: [main]\n pull_request:\n branches: [main]\n\njobs:\n buil"
},
{
"path": ".gitignore",
"chars": 67,
"preview": "node_modules\nreleases\ndist\ntmp\n.DS_Store\n.vscode\n.parcel-cache\n.env"
},
{
"path": ".husky/pre-commit",
"chars": 1,
"preview": "\n"
},
{
"path": ".npmrc",
"chars": 407,
"preview": "; Allow transitive dependency type access\nshamefully-hoist = true\n; Hard error on unsatisfied peer dependency requiremen"
},
{
"path": ".nvmrc",
"chars": 9,
"preview": "v20.17.0\n"
},
{
"path": ".prettierignore",
"chars": 92,
"preview": "**/node_modules\n**/dist\n**/tmp\nbuild\n**/package-lock.json\n.vscode/\n**/public/**\nCHANGELOG.md"
},
{
"path": ".prettierrc.js",
"chars": 92,
"preview": "module.exports = {\n singleQuote: true,\n arrowParens: 'always',\n trailingComma: 'none'\n};\n"
},
{
"path": "LICENSE.md",
"chars": 34198,
"preview": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. <"
},
{
"path": "README.md",
"chars": 2765,
"preview": "# Background Removal in the Browser & Node.js\n\n### 🚨 We are hiring 🚨\n\nWe are always looking for great people at IMG.LY. "
},
{
"path": "TODOS.md",
"chars": 347,
"preview": "# Todos\n\n## Todo 2.0\n\n- [ ] use logger/telemetry callback instead of custom debug output\n- [ ] use resolver callback ins"
},
{
"path": "bundle/models/isnet",
"chars": 134,
"preview": "version https://git-lfs.github.com/spec/v1\noid sha256:cc2c9f5c1751b9737cb81e708ff0c5e9542c2205daed22418a4fd2ab5d4c481a\ns"
},
{
"path": "bundle/models/isnet_fp16",
"chars": 133,
"preview": "version https://git-lfs.github.com/spec/v1\noid sha256:2eb4b5dda7ec41c617e59706e5aafa1f978c9a5f983d2518d9f0ae4d6eb04f20\ns"
},
{
"path": "bundle/models/isnet_quint8",
"chars": 133,
"preview": "version https://git-lfs.github.com/spec/v1\noid sha256:d1ca3535c21b53d08fa3b640e5949389f82e764f6376a0502d44982c35cae482\ns"
},
{
"path": "package.json",
"chars": 1633,
"preview": "{\n \"version\": \"1.7.0\",\n \"name\": \"workspace\",\n \"private\": true,\n \"bin\": {\n \"changelog-create\": \"./scripts/changelo"
},
{
"path": "packages/node/.resources.mjs",
"chars": 123,
"preview": "export default [\n {\n path: '/models/',\n source: '../../bundle/models/*',\n mime: 'application/octet-steam'\n }\n"
},
{
"path": "packages/node/CHANGELOG.md",
"chars": 1447,
"preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
},
{
"path": "packages/node/LICENSE.md",
"chars": 34198,
"preview": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. <"
},
{
"path": "packages/node/README.md",
"chars": 7641,
"preview": "# Background Removal in NodeJs\n\n### 🚨 We are hiring 🚨\n\nWe are always looking for great people at IMG.LY. If you are work"
},
{
"path": "packages/node/ThirdPartyLicenses.json",
"chars": 246,
"preview": "{\n \"onnxruntime-web\": {\n \"source\": \"https://www.npmjs.com/package/onnxruntime-node\",\n \"type\": \"code\",\n \"licens"
},
{
"path": "packages/node/changelog/1.2.0/20230811184244-export_type_and_formats.yml",
"chars": 169,
"preview": "---\ntype: Added\ndescription: Support `foreground`, `background` and `mask` export type.\n---\ntype: Added\ndescription: Add"
},
{
"path": "packages/node/changelog/1.2.1/20230811184244-Changelog_item.yml",
"chars": 160,
"preview": "---\ntype: Added\ndescription: |\n `CHANGELOG.md` for an better overview of the changes.\n---\ntype: Added\ndescription: |\n "
},
{
"path": "packages/node/changelog/1.3.0/20230612112304-progress_return_type.yaml",
"chars": 178,
"preview": "---\ntype: Changed\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Changed the return v"
},
{
"path": "packages/node/changelog/1.3.0/20231512181521-resource_data_chunking.yaml",
"chars": 184,
"preview": "---\ntype: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Resources are now chun"
},
{
"path": "packages/node/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml",
"chars": 713,
"preview": "---\ntype: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Output is now in the original image "
},
{
"path": "packages/node/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml",
"chars": 148,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Bumped o"
},
{
"path": "packages/node/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml",
"chars": 153,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Changed "
},
{
"path": "packages/node/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml",
"chars": 210,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added op"
},
{
"path": "packages/node/changelog/1.4.0/20242301155647-Typescript_bindings_are_generated_with_tsc.yaml",
"chars": 157,
"preview": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Typesc"
},
{
"path": "packages/node/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
"chars": 142,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added Th"
},
{
"path": "packages/node/changelog/Unreleased/.keep",
"chars": 0,
"preview": ""
},
{
"path": "packages/node/changelog/info.yml",
"chars": 262,
"preview": "---\ndescription: |\n All notable changes to this project will be documented in this file.\n\n The format is based on [Kee"
},
{
"path": "packages/node/package.json",
"chars": 2718,
"preview": "{\n \"name\": \"@imgly/background-removal-node\",\n \"version\": \"1.7.0\",\n \"description\": \"Background Removal in NodeJS\",\n \""
},
{
"path": "packages/node/scripts/build.mjs",
"chars": 811,
"preview": "export { configs };\nimport * as esbuild from 'esbuild';\nimport { readFileSync } from 'fs';\nimport path from 'path';\nimpo"
},
{
"path": "packages/node/scripts/watch.mjs",
"chars": 366,
"preview": "import * as esbuild from 'esbuild';\nimport { configs } from './build.mjs';\nimport dts from 'npm-dts';\n\nnew dts.Generator"
},
{
"path": "packages/node/src/codecs.ts",
"chars": 3581,
"preview": "export { imageEncode, imageDecode, MimeType };\n\nimport sharp, { FormatEnum } from 'sharp';\nimport ndarray, { NdArray } f"
},
{
"path": "packages/node/src/index.ts",
"chars": 4929,
"preview": "export default removeBackground;\nexport {\n removeBackground,\n removeForeground,\n segmentForeground,\n applySegmentati"
},
{
"path": "packages/node/src/inference.ts",
"chars": 1612,
"preview": "export { initInference, runInference };\n\nimport { tensorResizeBilinear, tensorHWCtoBCHW } from './utils';\nimport { creat"
},
{
"path": "packages/node/src/onnx.ts",
"chars": 1513,
"preview": "export { createOnnxSession, runOnnxSession };\n\nimport ndarray, { NdArray } from 'ndarray';\nimport * as ort from 'onnxrun"
},
{
"path": "packages/node/src/resource.ts",
"chars": 2496,
"preview": "export { loadAsBlob, loadAsUrl, loadFromURI };\n\nimport { Config } from './schema';\nimport { ensureAbsoluteURI } from './"
},
{
"path": "packages/node/src/schema.ts",
"chars": 2489,
"preview": "export { ConfigSchema, Config, validateConfig };\nimport { z } from 'zod';\nimport path from 'node:path';\nimport pkg from "
},
{
"path": "packages/node/src/url.ts",
"chars": 366,
"preview": "export { ensureAbsoluteURI };\n\nfunction isAbsoluteURI(url: string): boolean {\n const regExp = new RegExp('^(?:[a-z+]+:)"
},
{
"path": "packages/node/src/utils.ts",
"chars": 4129,
"preview": "export {\n imageDecode,\n imageEncode,\n tensorResizeBilinear,\n tensorHWCtoBCHW,\n calculateProportionalSize,\n imageSo"
},
{
"path": "packages/node/tsconfig.json",
"chars": 233,
"preview": "{\n \"compilerOptions\": {\n \"lib\": [\"DOM\", \"ES2015\"],\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true,\n \""
},
{
"path": "packages/node-e2e/fixtures/images/img2img.sh",
"chars": 477,
"preview": "filename=\"photo-1686002359940-6a51b0d64f68.jpeg\"\nbasename=\"${filename%.*}\"\n\ncp \"$filename\" \"$filename\".orig\nmagick \"$fil"
},
{
"path": "packages/node-e2e/package.json",
"chars": 180,
"preview": "{\n \"name\": \"e2e\",\n \"private\": true,\n \"scripts\": {},\n \"devDependencies\": {\n \"@imgly/background-removal-node\": \"wor"
},
{
"path": "packages/node-e2e/src/example.test.js",
"chars": 563,
"preview": "// const pkg = require('@imgly/background-removal-node');\n// const removeBackground = pkg.default;\n\n// Test case to ensu"
},
{
"path": "packages/node-examples/package.json",
"chars": 259,
"preview": "{\n \"name\": \"examples-node-cli\",\n \"private\": true,\n \"main\": \"index.mjs\",\n \"scripts\": {\n \"start\": \"node src/example"
},
{
"path": "packages/node-examples/src/example_001.cjs",
"chars": 1817,
"preview": "const {\n removeBackground,\n segmentForeground,\n applySegmentationMask\n} = require('@imgly/background-removal-node');\n"
},
{
"path": "packages/web/CHANGELOG.md",
"chars": 1901,
"preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Change"
},
{
"path": "packages/web/LICENSE.md",
"chars": 34198,
"preview": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. <"
},
{
"path": "packages/web/README.md",
"chars": 9106,
"preview": "# Background Removal in the Browser\n\nWe are always looking for great people at IMG.LY. If you are working with our backg"
},
{
"path": "packages/web/ThirdPartyLicenses.json",
"chars": 569,
"preview": "{\n \"onnxruntime-web\": {\n \"source\": \"https://www.npmjs.com/package/onnxruntime-web\",\n \"type\": \"code\",\n \"license"
},
{
"path": "packages/web/changelog/1.2.0/20230811184244-export_type_and_formats.yml",
"chars": 169,
"preview": "---\ntype: Added\ndescription: Support `foreground`, `background` and `mask` export type.\n---\ntype: Added\ndescription: Add"
},
{
"path": "packages/web/changelog/1.2.1/20230811184244-Changelog_item.yml",
"chars": 160,
"preview": "---\ntype: Added\ndescription: |\n `CHANGELOG.md` for an better overview of the changes.\n---\ntype: Added\ndescription: |\n "
},
{
"path": "packages/web/changelog/1.3.0/20230612112148-progress_return_type.yaml",
"chars": 178,
"preview": "---\ntype: Changed\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Changed the return v"
},
{
"path": "packages/web/changelog/1.3.0/20231512181521-resource_data_chunking.yaml",
"chars": 184,
"preview": "---\ntype: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Resources are now chun"
},
{
"path": "packages/web/changelog/1.3.0/20231512193816-upscale_mask_to_original_image.yaml",
"chars": 713,
"preview": "---\ntype: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Output is now in the original image "
},
{
"path": "packages/web/changelog/1.4.0/20233012103509-Moved.yaml",
"chars": 200,
"preview": "---\ntype: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Moved all data into it"
},
{
"path": "packages/web/changelog/1.4.0/20240702115710-Bumped_onnx_runtime_to_1_17_Changed.yaml",
"chars": 148,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Bumped o"
},
{
"path": "packages/web/changelog/1.4.0/20240702115731-Changed_license_from_GPL_to_AGPL_Changed.yaml",
"chars": 153,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Changed "
},
{
"path": "packages/web/changelog/1.4.0/20241601144157-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml",
"chars": 210,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added op"
},
{
"path": "packages/web/changelog/1.4.0/20241601144238-Added_option_to_apply_segmentation_mask_to_any_image_Used_for_applying_the_same_mask_to_srcsets_.yaml",
"chars": 210,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added op"
},
{
"path": "packages/web/changelog/1.4.0/20241601175908-Fallback_to_Canvas_if_OffscreenCanvas_is_not_available.yaml",
"chars": 169,
"preview": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Fallba"
},
{
"path": "packages/web/changelog/1.4.0/20242301155639-Typescript_bindings_are_generated_with_tsc.yaml",
"chars": 157,
"preview": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Typesc"
},
{
"path": "packages/web/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
"chars": 142,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added Th"
},
{
"path": "packages/web/changelog/1.5.0/20242403201534-Added_option_to_execute_on_gpu_webgpu_and_cpu_Added.yaml",
"chars": 195,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added op"
},
{
"path": "packages/web/changelog/1.5.0/20242503170808-Added_isnet_model_for_webgpu_Added.yaml",
"chars": 141,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added is"
},
{
"path": "packages/web/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
"chars": 135,
"preview": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Upgrad"
},
{
"path": "packages/web/changelog/Unreleased/.keep",
"chars": 0,
"preview": ""
},
{
"path": "packages/web/changelog/info.yml",
"chars": 262,
"preview": "---\ndescription: |\n All notable changes to this project will be documented in this file.\n\n The format is based on [Kee"
},
{
"path": "packages/web/package.json",
"chars": 2635,
"preview": "{\n \"name\": \"@imgly/background-removal\",\n \"version\": \"1.7.0\",\n \"description\": \"Background Removal in the Browser\",\n \""
},
{
"path": "packages/web/scripts/build.mjs",
"chars": 830,
"preview": "export { configs };\n\nimport * as esbuild from 'esbuild';\nimport { readFileSync } from 'fs';\nimport path from 'path';\nimp"
},
{
"path": "packages/web/scripts/watch.mjs",
"chars": 366,
"preview": "import * as esbuild from 'esbuild';\nimport { configs } from './build.mjs';\nimport dts from 'npm-dts';\n\nnew dts.Generator"
},
{
"path": "packages/web/src/MimeType.ts",
"chars": 1088,
"preview": "export class MimeType {\n type: string = 'application/octet-stream';\n params: Record<string, string> = {};\n\n private c"
},
{
"path": "packages/web/src/api/v1.ts",
"chars": 4970,
"preview": "export default removeBackground;\nexport {\n preload,\n removeBackground,\n removeForeground,\n alphamask,\n segmentForeg"
},
{
"path": "packages/web/src/capabilities.js",
"chars": 3855,
"preview": "export const bigInt = () =>\n (async (e) => {\n try {\n return (\n (await WebAssembly.instantiate(e)"
},
{
"path": "packages/web/src/codecs.ts",
"chars": 2330,
"preview": "export { imageEncode, imageDecode, MimeType };\nimport { MimeType } from './MimeType';\nimport { imageBitmapToImageData, c"
},
{
"path": "packages/web/src/index.ts",
"chars": 63,
"preview": "export * from './api/v1';\n// export * as next from './api/v2';\n"
},
{
"path": "packages/web/src/inference.ts",
"chars": 1946,
"preview": "export { initInference, runInference };\n\nimport { tensorResizeBilinear, tensorHWCtoBCHW } from './utils';\nimport { creat"
},
{
"path": "packages/web/src/onnx.ts",
"chars": 3079,
"preview": "export { createOnnxSession, runOnnxSession };\n\nimport ndarray, { NdArray } from 'ndarray';\nimport { InferenceSession, Te"
},
{
"path": "packages/web/src/resource.ts",
"chars": 3664,
"preview": "export { loadAsBlob, loadAsUrl, loadAsArrayBuffer, preload, resolveChunkUrls };\n\nimport { Config } from './schema';\n\nasy"
},
{
"path": "packages/web/src/schema.ts",
"chars": 2815,
"preview": "export { Config, ConfigSchema, validateConfig };\n\nimport { z } from 'zod';\n\nimport pkg from '../package.json';\n\nconst Co"
},
{
"path": "packages/web/src/types.d.ts",
"chars": 36,
"preview": "interface Navigator {\n gpu: any;\n}\n"
},
{
"path": "packages/web/src/url.ts",
"chars": 476,
"preview": "export { isAbsoluteURI, ensureAbsoluteURI };\n\nfunction isAbsoluteURI(url: string): boolean {\n const regExp = new RegExp"
},
{
"path": "packages/web/src/utils.ts",
"chars": 5205,
"preview": "export {\n imageDecode,\n imageEncode,\n tensorResizeBilinear,\n tensorHWCtoBCHW,\n imageBitmapToImageData,\n imageSourc"
},
{
"path": "packages/web/tsconfig.json",
"chars": 279,
"preview": "{\n \"compilerOptions\": {\n \"lib\": [\"DOM\", \"ESNext\"],\n \"resolveJsonModule\": true,\n \"esModuleInterop\": true,\n \""
},
{
"path": "packages/web-data/.resources.mjs",
"chars": 761,
"preview": "export default [\n {\n path: '/onnxruntime-web/',\n source:\n '../../node_modules/onnxruntime-web/dist/ort-wasm-"
},
{
"path": "packages/web-data/LICENSE.md",
"chars": 34198,
"preview": "# GNU Affero General Public License\n\n_Version 3, 19 November 2007_\n_Copyright © 2007 Free Software Foundation, Inc. <"
},
{
"path": "packages/web-data/ThirdPartyLicenses.json",
"chars": 245,
"preview": "{\n \"onnxruntime-web\": {\n \"source\": \"https://www.npmjs.com/package/onnxruntime-web\",\n \"type\": \"code\",\n \"license"
},
{
"path": "packages/web-data/changelog/1.4.5/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
"chars": 142,
"preview": "---\ntype: Added\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Added Th"
},
{
"path": "packages/web-data/changelog/1.5.6/20242602190400-Added_ThirdPartyLicenses_json_Added.yaml",
"chars": 135,
"preview": "---\ntype: Changed\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n Upgrad"
},
{
"path": "packages/web-data/package.json",
"chars": 1488,
"preview": "{\n \"name\": \"@imgly/background-removal-data\",\n \"version\": \"1.7.0\",\n \"description\": \"Background Removal Data\",\n \"keywo"
},
{
"path": "packages/web-examples/next-example/.gitignore",
"chars": 480,
"preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pn"
},
{
"path": "packages/web-examples/next-example/README.md",
"chars": 1450,
"preview": "This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-re"
},
{
"path": "packages/web-examples/next-example/eslint.config.mjs",
"chars": 391,
"preview": "import { dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { FlatCompat } from '@eslint/eslintrc';\n\ncon"
},
{
"path": "packages/web-examples/next-example/next.config.ts",
"chars": 133,
"preview": "import type { NextConfig } from 'next';\n\nconst nextConfig: NextConfig = {\n /* config options here */\n};\n\nexport default"
},
{
"path": "packages/web-examples/next-example/package.json",
"chars": 629,
"preview": "{\n \"name\": \"next-example\",\n \"version\": \"1.7.0\",\n \"private\": true,\n \"scripts\": {\n \"dev\": \"next dev\",\n \"build\": "
},
{
"path": "packages/web-examples/next-example/src/app/BackgroundRemoval.tsx",
"chars": 4541,
"preview": "'use client';\n\nimport {\n applySegmentationMask,\n Config,\n preload,\n removeBackground,\n segmentForeground\n} from '@i"
},
{
"path": "packages/web-examples/next-example/src/app/BackgroundRemovalNoSSR.tsx",
"chars": 186,
"preview": "'use client';\nimport dynamic from 'next/dynamic';\n\nconst BackgroundRemovalNoSSR = dynamic(() => import('./BackgroundRemo"
},
{
"path": "packages/web-examples/next-example/src/app/globals.css",
"chars": 1552,
"preview": ":root {\n --background: #ffffff;\n --foreground: #171717;\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n --backg"
},
{
"path": "packages/web-examples/next-example/src/app/layout.tsx",
"chars": 355,
"preview": "import type { Metadata } from 'next';\nimport './globals.css';\n\nexport const metadata: Metadata = {\n title: 'Create Next"
},
{
"path": "packages/web-examples/next-example/src/app/page.tsx",
"chars": 136,
"preview": "import BackgroundRemovalNoSSR from './BackgroundRemovalNoSSR';\n\nexport default function Home() {\n return <BackgroundRem"
},
{
"path": "packages/web-examples/next-example/tsconfig.json",
"chars": 602,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2017\",\n \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n \"allowJs\": true,\n "
},
{
"path": "packages/web-examples/vite-project/.gitignore",
"chars": 253,
"preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
},
{
"path": "packages/web-examples/vite-project/.vercel/README.txt",
"chars": 520,
"preview": "> Why do I have a folder named \".vercel\" in my project?\nThe \".vercel\" folder is created when you link a directory to a V"
},
{
"path": "packages/web-examples/vite-project/.vercel/project.json",
"chars": 98,
"preview": "{\n \"orgId\": \"team_JFznad5UXNe4xKmEfdbZq5jl\",\n \"projectId\": \"prj_jLTn0qO7rU5v6MEyaNREE9gIk3l2\"\n}\n"
},
{
"path": "packages/web-examples/vite-project/README.md",
"chars": 1527,
"preview": "# Vue 3 + TypeScript + Vite\n\nThis template should help get you started developing with Vue 3 and TypeScript in Vite. The"
},
{
"path": "packages/web-examples/vite-project/index.html",
"chars": 362,
"preview": "<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"/"
},
{
"path": "packages/web-examples/vite-project/package.json",
"chars": 543,
"preview": "{\n \"name\": \"vite-project\",\n \"private\": true,\n \"version\": \"1.7.0\",\n \"type\": \"module\",\n \"scripts\": {\n \"start\": \"pn"
},
{
"path": "packages/web-examples/vite-project/src/App.vue",
"chars": 5387,
"preview": "<script>\nimport { ref, watch, onMounted, onUnmounted } from 'vue';\n\nimport {\n preload,\n removeBackground,\n removeFore"
},
{
"path": "packages/web-examples/vite-project/src/main.ts",
"chars": 115,
"preview": "import { createApp } from 'vue';\nimport './style.css';\nimport App from './App.vue';\n\ncreateApp(App).mount('#app');\n"
},
{
"path": "packages/web-examples/vite-project/src/style.css",
"chars": 1327,
"preview": ":root {\n font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;\n line-height: 1.5;\n font-weight: 400;\n\n"
},
{
"path": "packages/web-examples/vite-project/src/vite-env.d.ts",
"chars": 38,
"preview": "/// <reference types=\"vite/client\" />\n"
},
{
"path": "packages/web-examples/vite-project/tsconfig.json",
"chars": 682,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"useDefineForClassFields\": true,\n \"module\": \"ESNext\",\n \"lib\":"
},
{
"path": "packages/web-examples/vite-project/tsconfig.node.json",
"chars": 213,
"preview": "{\n \"compilerOptions\": {\n \"composite\": true,\n \"skipLibCheck\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\""
},
{
"path": "packages/web-examples/vite-project/vite.config.ts",
"chars": 301,
"preview": "import { defineConfig } from 'vite';\nimport vue from '@vitejs/plugin-vue';\n\n// https://vitejs.dev/config/\nexport default"
},
{
"path": "pnpm-workspace.yaml",
"chars": 134,
"preview": "packages:\n - packages/*\n - packages/web-examples/*\nonlyBuiltDependencies:\n - esbuild\n - onnxruntime-node\n - protobu"
},
{
"path": "scripts/changelog/changelog-create.mjs",
"chars": 5204,
"preview": "#!/usr/bin/env node\n\nimport moment from 'moment';\nimport ejs from 'ejs';\nimport meow from 'meow';\nimport chalk from 'cha"
},
{
"path": "scripts/changelog/changelog-generate.mjs",
"chars": 3138,
"preview": "#!/usr/bin/env node\n\n/**\n * https://keepachangelog.com/en/1.1.0/\n * Idea is simple we have a directory of yaml files. Th"
},
{
"path": "scripts/changelog/template.yml.ejs",
"chars": 135,
"preview": "---\ntype: <%= type %>\n# type: Added\n# type: Changed\n# type: Removed\n# type: Security\n# private: true\ndescription: |\n "
},
{
"path": "scripts/deploy-assets.mjs",
"chars": 2853,
"preview": "import chalk from 'chalk';\nimport { exec } from 'child_process';\nimport { readFile } from 'node:fs/promises';\nimport { p"
},
{
"path": "scripts/package-resources.mjs",
"chars": 5613,
"preview": "export default main;\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {"
},
{
"path": "scripts/package-version.mjs",
"chars": 875,
"preview": "import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'glob';\n\nconst workspaceManifest = JSON"
}
]
About this extraction
This page contains the full source code of the imgly/background-removal-js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 124 files (268.9 KB), approximately 70.7k tokens, and a symbol index with 94 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.