How to process images from a local directory
A common use case for the Remove Background API is to process a large amount of images, which are stored in a local directory.
In this tutorial, we'll see how it's possible to process these images by integrating the Remove Background API with a Python script.
This tutorial takes example of processing images through the Remove Background API, but this approach would also work with our other APIs that accept a POST HTTP call: the Generate Background API and the Image Editing API Legacy.
Step 1: Calling the Remove Background API
First, we'll write a function that can process a local image through the Remove Background API and save the result image returned by the API to the disk:
This code is pretty straightforward:
it opens the image stored at
input_image_path
uses the
requests
library to make the POST HTTP call to the APIsaves the result image at
output_image_path
Notice that you will need to update the value of the constant API_KEY
with your own API key.
If you don't have an API key, here are the steps to create yours.
Step 2: Iterating over a local directory
Now that we have a function to process a single image, the next step is to iterate over all the images stored in a local directory and call process_image()
for each of them.
This time the code is a bit more complex, but here are its important steps:
we iterate over the files inside the directory at
input_directory_path
then for each
file
we:compose the
result_path
where the result image will be savedcheck that a file doesn't already exist at
result_path
(so as to not process the same image twice)call the function
process_image()
through anexecutor
, which allows us to execute 4 API calls in parallel
If you want, you can increase the value of the argument max_workers
to run more API calls in parallel. Keep in mind though that the API is rate limited to 500 calls/minutes.
Step 3: Running the script
We're almost there, the last thing we need is to actually run the script.
To do this we'll add this final piece of code:
Here we set the constants INPUT_DIRECTORY
and OUTPUT_DIRECTORY
to the paths of respectively:
the directory where the input images are stored
the directory where we want to save the result images.
Then all that's left is to actually run the script using the terminal:
Conclusion
In this tutorial, we saw how to use a Python script to easily process images stored locally with the Photoroom API.
We took the example of processing images through the Remove Background API, but this approach would also work with our other APIs that accept a POST HTTP call: the Generate Background API and the Edit Image API Legacy.
Download the code sample
Here's the entire code sample, if you want to easily save it to a file:
Last updated