首页 > 解决方案 > PIL 不保存透明度,而是带回背景

问题描述

字面意思就是这样。我正在使用 python 脚本从一个人的照片中删除背景,它做得相当不错。然后我用autocrop在图像上裁剪人的脸,然后我保存那张新照片。但是当我检查新图片时,它的背景又回来了,就像它之前没有被删除一样。为什么会发生,我该如何解决?欢迎任何帮助。预先感谢!

嗯,这就是我用来裁剪的代码

from PIL import Image
from autocrop import Cropper

cropper = Cropper()

# Get a Numpy array of the cropped image
cropper.face_percent = 80
cropped_array = cropper.crop('img/Italo1.png')

# Save the cropped image with PIL
cropped_image = Image.fromarray(cropped_array)
cropped_image.save('cropped.png')

下面删除了背景的图像(是的,不完全,但它可以满足我的需要) 删除背景的图像(是的,不完全,但它可以满足我的需要

这就是我裁剪后得到的图像 这是裁剪后的图像

那是试图删除背景的代码

from keras.models import load_model
from PIL import Image
from scipy.misc import imresize
import numpy as np
import tensorflow as tf
import cv2

# Load the pre-trained model
# provide main_model.hdf5 / main_model_2.hdf5 for the name of model
model = load_model('main_model.hdf5', compile=False)

graph = tf.get_default_graph()

def predict(image):
    with graph.as_default():
        # Make prediction
        prediction = model.predict(image[None, :, :, :])
    prediction = prediction.reshape((224,224, -1))
    return prediction

def main():
    print()
    print('##################################################################')
    print()
    path = input('Enter path of file: ')
    print()
    print('##################################################################')
    print()
    print("Removing background...")
    print()
    image = Image.open(path)
    image1 = imresize(image, (224, 224)) / 255.0

    prediction = predict(image1[:, :, 0:3])
    print('##################################################################')

    prediction = imresize(prediction[:, :, 1], (image.height, image.width))
    prediction[prediction>0.5*255] = 255
    prediction[prediction<0.5*255] = 0

    transparency = np.append(np.array(image)[:, :, 0:3], prediction[: , :, None], axis=-1)
    png = Image.fromarray(transparency)

    png.save('output.png')

    print()
    print("saved the output image in output.png")
    print()
    print('##################################################################')

if __name__ == '__main__':
    main()

标签: pythonnumpyimage-processingpython-imaging-library

解决方案


推荐阅读