图像中的背景移除

我想将图像的背景更改为白色。以下代码为我提供了黑色背景。输入图像具有白色背景。当我打印输出时,它显示黑色背景。输入图片如上

图像中的背景移除

import os
import sys
import random
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from skimage.io import imread,imshow,imread_collection,concatenate_images
from skimage.transform import resize
from skimage.morphology import label
import tensorflow as tf
X_train = np.zeros((len(train_ids),IMG_HEIGHT,IMG_WIDTH,IMG_CHANNELS),dtype=np.uint8)
Y_train = np.zeros((len(train_ids),1),dtype=np.uint8)
print('Getting and resizing train images and masks ... ')
sys.stdout.flush()
for n,id_ in tqdm(enumerate(train_ids),total=len(train_ids)):
    path = TRAIN_PATH +'\\'+ id_
    path_image = path + '\\images\\'
    path_mask = path + '\\masks\\'
    for image_file,mask_file in zip(os.listdir(path_image),os.listdir(path_mask)):
        img=imread(path_image+image_file)[:,:,:IMG_CHANNELS]
        img = resize(img,(IMG_HEIGHT,IMG_WIDTH),mode='constant',preserve_range=True)
        X_train[n] = img
        print(path_mask)
        print(mask_file)
        img2=imread(path_mask+mask_file)[:,:IMG_CHANNELS]
        img1 = resize(img2,preserve_range=True)
        Y_train[n] = img1
        #print(img2[0][0])
        plt.imshow(img2)
        plt.show()
tbdys 回答:图像中的背景移除

实际上,背景已经是黑色(RGB值为0),但由于它是完全透明的(alpha值为0)而显得白色。用 img=imread(path_image+image_file)[:,:,:IMG_CHANNELS] 您正在删除Alpha通道(假设IMG_CHANNELS = 3),该通道包含图像中像素的透明度。由于没有更多的透明度,因此背景现在显示为黑色。如果要使图像保持RGB格式,则可以在alpha通道为0的任何地方将像素设置为白色(如@HansHirse在注释中建议的那样):

from skimage.io import imread

img_rgba = imread('https://i.stack.imgur.com/BmIUd.png')

# split RGB channels and alpha channel
img_rgb,img_a = img_rgba[...,:3],img_rgba[...,3]
# make all fully transparent pixels white
img_rgb[img_a == 0] = (255,255,255)

Result

如果您仍然希望叶子边缘在RGB中看起来相同,则还可以查看Convert RGBA PNG to RGB with PIL的答案。 否则,应将图像保留为RGBA格式。

本文链接:https://www.f2er.com/2897655.html

大家都在问