Skip to content

Removing Backgrounds

We’re going to walk through how to take an input image, create a mask for the background, and use it to remove the background leaving just the foreground.

We’ll be using one of our cute puppies-in-the-clouds gens as our input image:

input.jpg

Once we are finished we’ll have removed the clouds and we be left with just cute puppies.

Project Setup

Terminal window
# Create a project directory.
mkdir prodia-removing-backgrounds
cd prodia-removing-backgrounds

Install Node (if not already installed):

Terminal window
brew install node
# Close the current terminal and open a new one so that node is available.

Create project skeleton:

Terminal window
# Requires node --version >= 18
# Initialize the project with npm.
npm init -y
# Install the prodia-js library.
npm install prodia --save
Terminal window
# Export your token so it can be used by the main code.
export PRODIA_TOKEN=your-token-here

Create a main file for your project:

main.js
const { createProdia } = require("prodia/v2");
const prodia = createProdia({
token: process.env.PRODIA_TOKEN // get it from environment
});

You’re now ready to make some API calls!

Get a mask for the background pixels

Terminal window
npm install sharp --save
main.js
const { createProdia } = require("prodia/v2");
const sharp = require("sharp");
const prodia = createProdia({
token: process.env.PRODIA_TOKEN,
});
(async () => {
// get input image
const inputBuffer = await (await fetch("https://docs.prodia.com/flux-styles-output.jpg")).arrayBuffer();
await sharp(inputBuffer).toFile("flux-styles-output.jpg");
// run a flux schnell generation
const job = await prodia.job({
type: "inference.mask-background.v1",
}, {
inputs: [ inputBuffer ]
});
const maskBuffer = await job.arrayBuffer();
await sharp(maskBuffer).toFile("mask.png");
})();
Terminal window
node main.js
Terminal window
open mask.png

mask.png

Selecting the foreground

Terminal window
npm install sharp --save
main.js
const { createProdia } = require("prodia/v2");
const sharp = require("sharp");
const prodia = createProdia({
token: process.env.PRODIA_TOKEN,
});
(async () => {
// get input image
const inputBuffer = await (await fetch("https://docs.prodia.com/flux-styles-output.jpg")).arrayBuffer();
await sharp(inputBuffer).toFile("flux-styles-output.jpg");
// run a flux schnell generation
const job = await prodia.job({
type: "inference.mask-background.v1",
}, {
inputs: [ inputBuffer ]
});
const maskBuffer = await job.arrayBuffer();
await sharp(maskBuffer).toFile("mask.png");
let foregroundImage = await sharp(inputBuffer).ensureAlpha().joinChannel(maskBuffer);
await foregroundImage.toFile("foreground.png");
})();
Terminal window
node main.js
Terminal window
open foreground.png

foreground.png