Reputation: 211
I want to change the background of an image to white. The following code gives me a black background. the input image has a white background. when i print output, it shows black background. Input image is given above
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), IMG_HEIGHT, IMG_WIDTH, 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, (IMG_HEIGHT, IMG_WIDTH,1), preserve_range=True)
Y_train[n] = img1
#print(img2[0][0])
plt.imshow(img2)
plt.show()
Upvotes: 0
Views: 1193
Reputation: 2779
Actually the background was already black (RGB values of 0), but it appeared white because it was completely transparent (alpha values of 0). With
img=imread(path_image+image_file)[:,:,:IMG_CHANNELS]
you are removing the alpha channel (assuming IMG_CHANNELS = 3
), which contains the transparency of the pixels in the image. Since there is no more transparency, the background now appears black. If you want to keep the image in RGB format, you can make the pixels white wherever the alpha channel is 0 (as @HansHirse suggested in a comment):
from skimage.io import imread
img_rgba = imread('https://i.sstatic.net/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)
You can also take a look at the answers of Convert RGBA PNG to RGB with PIL if you still want the leaf edges to look the same in RGB. Otherwise you should keep your image in RGBA format.
Upvotes: 2