Transparent images

      Comments Off on Transparent images

As we discussed last week here – Flux training on Replicate, nowadays it’s possible to generate all kind of images with AI. However there are two things image models are not yet good at – writing text on the images and generating transparent ones. On other side, in web development we often need icons or logos, which can’t be simply put on any background, so here are a few ways to remove the background from your freshly generated images. We will look into an approach to do it with python and then with php.

  1. In the prompt specify a background, on which the image will be generated – white, yellow or whatever other easy to determine color. A constant background makes it easier to be removed programatically.
  2. Python approach: we can use the PIL(Pillow) library for image processing, identify the background color and remove it, but it’s a way easier to use rembg https://github.com/danielgatis/rembg. Rembg is a tool to remove backgrounds from images and works quite well in my experience. Can be used via cli as well. Let’s see an example.
pip install rembg

from rembg import remove
from PIL import Image

def remove_background(input_path, output_path):
    """
    Remove background from an image using rembg.
    
    Args:
        input_path (str): Path to the input image
        output_path (str): Path to save the output image
    """
    # Open the input image
    input_image = Image.open(input_path)
    
    # Remove the background
    output_image = remove(input_image)
    
    # Save the output image
    output_image.save(output_path)

# Example usage
if __name__ == "__main__":
    remove_background(
        input_path="input_image.png",
        output_path="output_transparent.png"
    )

I made one of my LoRA models to generate me an icon for yoga studio on a beige background. And here is the result with rembg:

3. PHP approach – in php we can use the gd image library to draw a new transparent image and copy over it all the pixels that differ in color than the background.

<?php

function remove_background($input_path, $output_path, $tolerance = 30) 
{
    $source = imagecreatefromjpeg($input_path);
    $width = imagesx($source);
    $height = imagesy($source);

    $new_image = imagecreatetruecolor($width, $height);
    imagealphablending($new_image, false);
    imagesavealpha($new_image, true);
    
    $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
    imagefilledrectangle($new_image, 0, 0, $width, $height, $transparent);

    $corners = array(
        imagecolorsforindex($source, imagecolorat($source, 0, 0)),
        imagecolorsforindex($source, imagecolorat($source, $width-1, 0)),
        imagecolorsforindex($source, imagecolorat($source, 0, $height-1)),
        imagecolorsforindex($source, imagecolorat($source, $width-1, $height-1))
    );

    for ($x = 0; $x < $width; $x++) {
        for ($y = 0; $y < $height; $y++) {
            $rgb = imagecolorat($source, $x, $y);
            $colors = imagecolorsforindex($source, $rgb);
            
            $is_background = false;
            foreach ($corners as $corner) {
                if (abs($colors['red'] - $corner['red']) < $tolerance &&
                    abs($colors['green'] - $corner['green']) < $tolerance &&
                    abs($colors['blue'] - $corner['blue']) < $tolerance) {
                    $is_background = true;
                    break;
                }
            }
            
            if (!$is_background) {
                $color = imagecolorallocatealpha(
                    $new_image,
                    $colors['red'],
                    $colors['green'],
                    $colors['blue'],
                    $colors['alpha']
                );
                imagesetpixel($new_image, $x, $y, $color);
            }
        }
    }

    imagepng($new_image, $output_path);
    imagedestroy($source);
    imagedestroy($new_image);
    
    return true;
}

remove_background('input.jpg', 'output.png', 30);

What we do here:

  • Create new trasperant image with imagecreatetruecolor()
  • Sample colors from all four corners of original image. Assumption: corners usually contain background color.
  • Pixel Processing: For each pixel: Compare its color to corner colors. If the color is similar (within tolerance) to any corner = background. If background = leave transparent, if not background = copy pixel to new image.

Here is the result:

Of course none of these approaches works perfectly in all cases, but we can get pretty good results, especially with some more experimenting with the background color and the code settings. Enjoy!

WordPress

WordPress is my passion and love! Started as a blog system it turns in a really powerful CMS to allow us create professional, functional and really good looking web sites. WordPress also offers us a great community to help us, to develop amazing plugins and themes and to create a new better versions with more and more features. I have worked with different frameworks based on WordPress, created and customized themes and plugins so if my experience can help - you are welcome!