LoginSignup
1
0

More than 1 year has passed since last update.

Mattingはセグメンテーションの境界をくっきりさせる

Mattingには、trimap画像が必要

セグメンテーション・マスクの境界をよりくっきり強化するmattingには、trimap画像が必要です。
trimapは、マスクの境界の、オブジェクトか背景か曖昧な部分がグレーになっている画像です。
しかし、人力でtrimapを作るのは時間と手間がかかります。

マスク画像から自動でtrimapを作る方法

U2netなどでマスク画像を作り、以下の関数でtrimapを作成します。

import numpy as np
from scipy.ndimage import binary_erosion
import cv2

def make_trimap(mask,foreground_threshold=240,background_threshold=10,erode_structure_size=10): 
    # erode_structure_size で曖昧な領域の侵食度合いを決定します。
    is_foreground = mask > foreground_threshold
    is_background = mask < background_threshold
    
    structure = None
    if erode_structure_size > 0:
        structure = np.ones(
            (erode_structure_size, erode_structure_size), dtype=np.uint8
        )
    
    is_foreground = binary_erosion(is_foreground, structure=structure)
    is_background = binary_erosion(is_background, structure=structure, border_value=1)
    
    trimap = np.full(mask.shape, dtype=np.uint8, fill_value=128)
    trimap[is_foreground] = 255
    trimap[is_background] = 0
    return trimap
mask = cv2.imread("mask.jpg")
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) # if your mask image has 3 channel.
trimap = make_trimap(mask)

画像
pexels-pixabay-45201

マスク
result (63)

トライマップ
trimap

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0