My JPG image has a white background around it. I don’t want to change the image itself, I just want to make the white background transparent.Here is the code:
import cv2
import numpy as np
from PIL import Image
# 文件路径和文件名
path = "images/"
filename = "demo.jpg"
input_filepath = path + filename
output_filepath = path + "demo_transparent.png"
# 读取彩色图像
img = cv2.imread(input_filepath)
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 定义阈值
thresh = 250
# 阈值化图像
_, binary = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY)
# 查找图像中的轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建一个全白的掩码
mask = np.ones_like(gray) * 255
# 绘制找到的轮廓,填充内部区域
cv2.drawContours(mask, contours, -1, 0, thickness=cv2.FILLED)
# 反转掩码
mask = cv2.bitwise_not(mask)
# 将原图转换为包含透明通道的图像
rgba = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
# 遍历图像像素,将白色背景变为透明
height, width = mask.shape
for y in range(height):
for x in range(width):
if mask[y, x] == 255 and np.all(rgba[y, x][:3] == 255):
rgba[y, x][3] = 0 # 设置Alpha通道为0(透明)
# 将结果保存为PNG图像
result = Image.fromarray(rgba)
result.save(output_filepath)
print(f"Processed image saved at: {output_filepath}")
This code does help me make the white background around the image transparent, but it also changes the color of the image. I would like to ask how to keep the original image? Thanks.
I tried asking ChatGTP to help me out but he is no smarter than a human.
Jay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.