深度学习中利用黑白蒙版进行抠图
import cv2 import numpy as np def get_alpha(image, mask): # 归一化 mask = mask/255 back_mask = mask # 将透明度A值转成一样维度 back_transparent = back_mask.reshape(back_mask.shape[0], back_mask.shape[1], 1) # 将前景透明 fore_mask = 1-mask fore_transparent = fore_mask.reshape(fore_mask.shape[0], fore_mask.shape[1], 1) # 蒙上做计算 foreground_alpha = image * np.expand_dims(back_mask, axis=2).repeat(3, 2) / 255 background_alpha = image * np.expand_dims(fore_mask, axis=2).repeat(3, 2) / 255 # 加上透明度 foreground_alpha = np.c_[foreground_alpha, back_transparent] background_alpha = np.c_[background_alpha, fore_transparent] # print(foreground_alpha.shape) # 乘回原来的颜色 foreground_alpha = (foreground_alpha * 255).astype(np.uint8) background_alpha = (background_alpha * 255).astype(np.uint8) return foreground_alpha, background_alpha if __name__ == '__main__': input_path = r'C:\Users\Administrator.DESKTOP-161KJQD\Desktop\pyy.jpeg' mask_path = r'C:\Users\Administrator.DESKTOP-161KJQD\Desktop\pyy_mask.png' input_image = cv2.imread(input_path) mask_image = cv2.imread(mask_path) mask_image = cv2.cvtColor(mask_image, cv2.COLOR_BGR2GRAY) foreground_alpha, background_alpha = get_alpha(input_image, mask_image) cv2.imshow('foreground_alpha', foreground_alpha) cv2.imshow('background_alpha', background_alpha) cv2.imwrite(r'C:\Users\Administrator.DESKTOP-161KJQD\Desktop\foreground_alpha.png', foreground_alpha) cv2.imwrite(r'C:\Users\Administrator.DESKTOP-161KJQD\Desktop\background_alpha.png', background_alpha) cv2.waitKey(0) cv2.destroyAllWindows()
原图
蒙版
得到前景和背景
标签:透明,foreground,python,cv2,image,mask,蒙版,background,alpha From: https://www.cnblogs.com/moon3496694/p/18247254