通过https://developer.aliyun.com/article/1061353?spm=a2c6h.14164896.0.0.2cb72f4aSW18B1 提到的分割能力,我们可以很轻松的获取一张带有mask的png图片,获取该图片之后,我们可以通过下述方法实现替换背景的功能。这里我拿python做示例代码。
# *- author: ALIBABA DAMO AIC -* # *- date: 2020/12/14 -* import cv2 import numpy as np def picture_mergeBG(args): assert (args.files is not None and len(args.files) > 3), "parameters wrong, use -h for details!" of_file = args.files[3] [sc_image, viapi_image, bg_image] = [cv2.imread(img_file, cv2.IMREAD_UNCHANGED) for img_file in args.files[0:3]] assert (sc_image is not None and viapi_image is not None and bg_image is not None), "read image files error!" h, w, c = sc_image.shape viapi_image = cv2.resize(viapi_image, (w, h)) bg_image = cv2.resize(bg_image, (w, h)) if len(viapi_image.shape) == 2: mask = viapi_image[:, :, np.newaxis] if viapi_image.shape[2] == 4: mask = viapi_image[:, :, 3:4] elif viapi_image.shape[2] == 3: mask = viapi_image[:, :, 0:1] else: raise Exception("invalid image mask!") mask = mask / 255.0 sc_image = sc_image.astype(np.float) bg_image = bg_image.astype(np.float) of_image = (sc_image - bg_image) * mask + bg_image of_image = np.clip(of_image, 0, 255) cv2.imwrite(of_file, of_image)