python - 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()
解决方案
推荐阅读
- regex - Splunk:从仪表板的源代码中转义“<”>“
- excel - 按 TAB 后选择特定单元格
- excel - VBA,在 Excel 公式中引用另一个工作表的名称
- python - 如何找到一个点位于 GeoPandas DataFrame 的哪个多边形内?
- python - 无法在 cygwin 中使用 python 2.7
- javascript - 如何将网络摄像头流从 javascript 连接到 django 后端?
- python - 将时间戳从数据框列转换为日期格式
- swift - SwiftUI 在后台或主线程中渲染和布局?
- c++ - 如何在 C++ 中为堆栈动态创建结构?
- android - 无法在 android 上加载量化的 pytorch 移动模型