python利用蒙版進行摳圖,背景透明和前景透明

Wchime發表於2024-06-14

深度學習中利用黑白蒙版進行摳圖

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

原圖

蒙版

得到前景和背景

相關文章