Removing Black Background and Make Transparent using Python OpenCV

Removing Black Background and Make Transparent using Python OpenCV

If you want to remove a black background from an image and make it transparent using OpenCV in Python, you can follow these steps:

  • First, install the required libraries:
pip install opencv-python-headless numpy 
  • Implement the background removal:
import cv2 import numpy as np def remove_black_background(input_path, output_path): # Read the image img = cv2.imread(input_path, cv2.IMREAD_UNCHANGED) # Check if the image has a fourth channel (alpha channel for transparency) # If not, create one if img.shape[2] == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA) # Define a threshold to determine what is 'black' thresh = [40, 40, 40] # Create a mask of all pixels that are 'black' mask = (img[:, :, 0:3] < thresh).all(2) # Change all pixels that match the mask to be transparent img[mask] = [0, 0, 0, 0] # Save the result cv2.imwrite(output_path, img) # Example usage remove_black_background("path_to_input_image.png", "path_to_output_image.png") 

This function works by first checking if the input image has a transparency channel. If it doesn't, it adds one. The function then creates a mask of all pixels that are considered "black" (or nearly black, as defined by the thresh list). Finally, it sets all those pixels to be transparent and saves the result.

You might need to adjust the thresh values depending on the exact color of the background you want to remove and the quality of the image. The lower the values, the stricter the threshold for what is considered "black".


More Tags

micro-optimization import geoserver laravel-migrations ngfor hibernate-validator square nth-root event-loop controlvalueaccessor

More Programming Guides

Other Guides

More Programming Examples