My Coding >
Artificial Intelligence >
Image improvement with AI >
Removing image background with rembg library
Removing image background with rembg libraryRemoving the image background was a pretty simple but time-consuming task for designers. With Python, you can write the script, and remove the background for images in a few minutes and it will work very fast. With this script, you can process hundreds of images per hour. In this article, I will show you how to make this code and what problems you can face there. Removing image backgroundWe have a lovely duck image where we need to remove the background.
This is a very common task and we need to know how to do it easily, so, let's do it! Python code for background removalWe have two different ways to work with this task Transparent backgroundWe can remove the background and make everything transparent outside our object. First of all, we need to load libraries.
rembg - AI library for background removing. On the first run, it will upload all necessary trained models for background removal.
That it. img_out already an array with removed background, which we need to save:
If you actually need to have removed (transparent) background you need to save it as a PNG file format. Otherwise, the background will be black Make a specific colourIt is possible to make any background you like. Unfortunately, with rembg you can't do this and it is necessary to use PIL library for this.
Then, when we make a new image with the removed background as an array
Then, we need to do the following steps: convert this image to a PIL image, create a new background image of the same size with the desired colour or picture (new background) and then add our image using the mask of our image. And finally, save it!
It is highly likely, that the image will have strange colours
As you can see, the background is perfect, but the colour scheme is wrong, so we need to convert it to a proper RGB. To do so, we need to split our image into colour layers, and then merge them back in a different order and save it again.
This is our video with a more detailed explanation:
|
Last 10 artitles
9 popular artitles
|
|||||||||
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |