使用语义分割进行图像前景后景分离处理使用语义分割进行图像前景后景分离处理
在我们以前的文章中,我们学习了什么是语义分割,以及如何在PyTorch中使用DeepLabv3来获得图像中检测到的对象的RGB掩码。即我们将图
像中的对象标识出来。
虽然语义分割是很酷,但让我们看看如何在一些现实世界的应用程序中使用语义分割的处理结果。 在这篇文章中,我们将在torchvision中使用
DeepLabv3制作以下应用程序。
1、去掉背景
2、改变背景
3、模糊背景
4、背景灰度化
如果您没有阅读我们以前关于使用torchvision进行语义分割的帖子,请最好先阅读下,因为我们将修改该帖子中使用的一些方法,并跳过该帖子
中包含的一些详细注解信息。
1、删除背景、删除背景
让我们选择一个真实的应用程序进行演示。 假设你拥有一个在线销售二手车的网站。. 你的网站上的卖家上传他们的二手车的照片。由于大多数
卖家都不是老练的摄影师,所以你不能期望他们拍出有良好背景的照片。您可能还希望你的网页风格一致,要求所有的图片有相同的纯色背景。
在这个例子中,我们将看到如何删除汽车图片上的背景,在下面的部分中,我们将使用DeepLabV3来实现这一点。先看完整代码:
import os
from google.colab import drive
drive.mount('/content/drive')
path = "/content/drive/My Drive/Colab Notebooks"
os.chdir(path)
os.listdir(path)
from torchvision import models
from PIL import Image
import matplotlib.pyplot as plt
import torch
import numpy as np
import cv2
# Apply the transformations needed
import torchvision.transforms as T
# Define the helper function
def decode_segmap(image, source, nc=21):
label_colors = np.array([(0, 0, 0), # 0=background
# 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle
(128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128),
# 6=bus, 7=car, 8=cat, 9=chair, 10=cow
(0, 128, 128), (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0),
# 11=dining table, 12=dog, 13=horse, 14=motorbike, 15=person
(192, 128, 0), (64, 0, 128), (192, 0, 128), (64, 128, 128), (192, 128, 128),
# 16=potted plant, 17=sheep, 18=sofa, 19=train, 20=tv/monitor
(0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128)])
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
for l in range(0, nc):
idx = image == l
r[idx] = label_colors[l, 0] g[idx] = label_colors[l, 1] b[idx] = label_colors[l, 2] rgb = np.stack([r, g, b], axis=2)
# Load the foreground input image
foreground = cv2.imread(source)
print('foreground1')
print(foreground)
# Change the color of foreground image to RGB
# and resize image to match shape of R-band in RGB output map
foreground = cv2.cvtColor(foreground, cv2.COLOR_BGR2RGB)
foreground = cv2.resize(foreground, (r.shape[1], r.shape[0]))
print('foreground2')
# Create a background array to hold white pixels
# with the same size as RGB output map
background = 255 * np.ones_like(rgb).astype(np.uint8)
# Convert uint8 to float
foreground = foreground.astype(float)
background = background.astype(float)
# Create a binary mask of the RGB output map using the threshold value 0
th, alpha = cv2.threshold(np.array(rgb), 0, 255, cv2.THRESH_BINARY)
# Apply a slight blur to the mask to soften edges
print('alpha1')
print(alpha)
alpha = cv2.GaussianBlur(alpha, (7, 7), 0)
评论0