【问题标题】:Background removing in an image去除图像中的背景
【发布时间】:2020-04-11 05:45:16
【问题描述】:

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

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()

【问题讨论】:

  • 您可以将背景像素的值从 0 更改为 255(对于 8 位图像)
  • @Dr.H.Lecter 在我的形象中,有一些黑点必须留下。如果我改变像素值,我认为那些黑点也会消失
  • 请想一想人们可能需要什么来回答你……你没有提供任何输入图像,也没有任何迹象表明你期望什么输出。您还删除了 import 语句,因此我们不知道您是使用 OpenCV 还是 imageio 或其他方式来加载图像。
  • @MarkSetchell 代码太长,无法发布。希望这可以帮助。谢谢队友
  • @nathancy 实际上,背景是黑色的,但背景的 alpha 通道是(也)0,所以图像背景在 Stack Overflow 的白色背景上只是显示为白色。解决方案很简单:由于对象似乎有> 0 alpha 通道,而背景有0 alpha 通道,只需将图像的RGB 值设置为(255, 255, 255),其中alpha 通道为0。还克服了可能保留对象内现有黑色像素的问题。另一种方法是找到对象的轮廓,遮盖背景并将其设置为白色。

标签: python numpy image-processing scikit-image


【解决方案1】:

实际上背景已经是黑色(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)

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

【讨论】:

    猜你喜欢
    • 2015-04-14
    • 1970-01-01
    • 2017-03-19
    • 2021-04-07
    • 2021-01-12
    • 2023-03-17
    • 1970-01-01
    • 2011-07-27
    • 2017-07-09
    相关资源
    最近更新 更多