Created
February 24, 2023 10:27
-
-
Save DynamiteC/b0114359095d04b9bf7271e9e401377d to your computer and use it in GitHub Desktop.
Remove White Background From Image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
# Read the input image | |
img = cv2.imread('input.png') | |
# Convert the image to grayscale | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
# Threshold the image to create a binary mask | |
_, mask = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY) | |
# Invert the mask | |
mask_inv = cv2.bitwise_not(mask) | |
# Split the image channels | |
b, g, r = cv2.split(img) | |
# Add an alpha channel to the image | |
alpha = np.ones_like(gray) * 255 | |
# Set the alpha channel for the background to 0 | |
alpha[mask == 255] = 0 | |
# Merge the channels with the alpha channel | |
img_rgba = cv2.merge((b, g, r, alpha)) | |
# Save the result image with transparency | |
cv2.imwrite('output.png', img_rgba) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment