簡單實現思路:python
在這裏,使用DeepLabV3模型對圖像內容進行分割並提取人像,實現的代碼以下:優化
import numpy as np import tensorflow as tf import cv2 from deeplabmodel import * def create_pascal_label_colormap(): colormap = np.zeros((256, 3), dtype=int) ind = np.arange(256, dtype=int) for shift in reversed(range(8)): for channel in range(3): colormap[:, channel] |= ((ind >> channel) & 1) << shift ind >>= 3 return colormap def label_to_color_image(label): if label.ndim != 2: raise ValueError('Expect 2-D input label') colormap = create_pascal_label_colormap() if np.max(label) >= len(colormap): raise ValueError('label value too large.') return colormap[label] def load_model(): model_path = '../resources/models/tensorflow/deeplabv3_mnv2_pascal_train_aug_2018_01_29.tar.gz'#'deeplab_model.tar.gz' MODEL = DeepLabModel(model_path) print('model loaded successfully!') return MODEL model = load_model() src = cv2.imread('../resources/images/person2.jpg') resized_im, seg_map = model.run2(src) seg_image = label_to_color_image(seg_map).astype(np.uint8) print(seg_map.dtype) # seg_map = cv2.GaussianBlur(np.uint8(seg_map),(11,11),0) src_resized = cv2.resize(src,(resized_im.shape[1],resized_im.shape[0])) seg_image = cv2.GaussianBlur(seg_image,(11,11),0) bg_img = np.zeros_like(src_resized) bg_img[seg_map == 0] = src_resized[seg_map == 0] blured_bg = cv2.GaussianBlur(bg_img,(11,11),0) result = np.zeros_like(bg_img) result[seg_map > 0] = resized_im[seg_map > 0] result[seg_map == 0] = blured_bg[seg_map == 0] cv2.imshow("seg_image",seg_image) cv2.imshow('bg_image',bg_img) cv2.imshow('blured_bg',blured_bg) cv2.imshow('result',result) cv2.waitKey() cv2.destroyAllWindows()
原圖:ui
人像提取結果:code
背景圖像:orm
背景模糊圖像:blog
合成結果:input
效果不太理想,但整體上實現了背景虛化。後期將進行細節優化。it