numpy 用蒙版获得透明背景,我得到白色背景

owfi6suc  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(201)
def combined_display(image, matte):
  # calculate display resolution
  w, h = image.width, image.height
  rw, rh = 800, int(h * 800 / (3 * w))

  # obtain predicted foreground
  image = np.asarray(image)
  if len(image.shape) == 2:
    image = image[:, :, None]
  if image.shape[2] == 1:
    image = np.repeat(image, 3, axis=2)
  elif image.shape[2] == 4:
    image = image[:, :, 0:3]
  matte = np.repeat(np.asarray(matte)[:, :, None], 3, axis=2) / 255
  foreground = image * matte + np.full(image.shape, 255) * (1 - matte)

  foreground =  Image.fromarray(np.uint8(foreground))
  foreground.save("imag.png", format="png")
  return foreground

我正在尝试获得透明的背景,比如Remvebg,我不想要白色的背景。请帮我去除背景,得到透明的背景。

beq87vna

beq87vna1#

假设您有一个3通道图像和一个1通道蒙版。然后,您可以将它们堆叠在一个4通道图像中,其中最后一个通道负责透明度。

import numpy as np
from PIL import Image

image = Image.open('image.png')
mask = Image.open('mask.png').convert('L')

image_with_transparency = np.dstack((image, mask))

Image.fromarray(image_with_transparency).save('image_trs.png')

结果是:

相关问题