正在删除黑色背景图像



我想删除此图像的黑色背景。我如何在python中做到这一点?我已经试过通过opencv做了,但它不起作用

import numpy as np
import matplotlib.pyplot as plt
import cv2
from PIL import Image


# CODE TO ELIMINATE BLACK BACKGROUND
def remove_background(image):
image = image.convert("RGBA")
datas = image.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255,0,0,0))
else:
newData.append((item))
image.putdata(newData)
transparent_image = np.asarray(image)
return transparent_image

# remove background
bozu = Image.open("QWERTY.png")
transparent_bozu = remove_background(bozu)
from google.colab.patches import cv2_imshow
cv2_imshow(transparent_bozu)
plt.imshow(transparent_bozu)
plt.show()

循环移除的是白色像素,而不是黑色像素(RGB值(255,255,255)。黑色为(0,0,0)(。此外,使用numpy,而不是手动循环数据并使用列表:

import numpy as np
import PIL
def remove_background(image: PIL.Image):
image = np.asarray(image.convert("RGBA"))
idx = (image[...,:3] == np.array((0,0,0))).all(axis=-1)
im[idx,3] = 0
return PIL.Image.fromarray(im)

相关线路为:

idx = (image[...,:3] == np.array((0,0,0))).all(axis=-1)

首先,查找图像中RGB值为(0,0,0)的所有像素。最后的.all()是为了确保只获得三个值都为0的像素,而不仅仅是其中的一个。

然后,使用该索引,将索引为True:的像素中的alpha通道归零

im[idx,3] = 0

最新更新