備註:該代碼框架從https://blog.csdn.net/u011630458/article/details/78323136的global-matting筆記總結而來,感謝羽凌寒對global-matting代碼框架的梳理。
輸入:1、src
2、mask(0爲背景,128未知區域,255爲前景)
輸出:alpha-matte
# 根據前後景圖像與周圍未知區域的顏色、強度相關性,對圖像掩碼mask做一定程度的前後景擴散,然後腐蝕。
1、expansionOfKnownRegions
2、找mask的前景和unknown區域的邊界位置,存入:fore_Boundary ;找mask背景和未知區域邊界位置,存入:back_Boundary
# generate global-samples set
3、隨機生成:fore_Boundary.size + back_Boundary.size個座標點,如果該座標位置mask像素值爲255或者0,
則將該點座標對應放入fore_Boundary或者back_Boundary。
4、根據fore_Boundary和back_Boundary中存放的座標點的對應src圖像信息強度從小到大對座標點進行排序。
5、對於mask未知區域中的每個點:
計算每個未知區域點和fore_Boundary、back_Boundary的最小座標距離平方差。
並隨機生成(rand()%fore_Boundary.size(), rand()%back_Boundary.size())全部存入到samples中。
# samples中數據存儲格式:[y, x, d, fi, bj, alpha, cost]
6、建立數組二維coords,存入src圖像座標從(0,0)到(h,w)存入。
7、循環10次:
將coords存的座標數據隨機打亂從排。
# propagation ...
for i in range(coords.size()):
取出mask[coords[i].x, coords[i].y]數據
if(mask != 128)
continue;
else
取出src該點像素與samples該點參數(s1)。
以(coords[i].x, coords[i].y)爲中心的3x3矩形遍歷(索引用[p][q]表示): # shared-info
if(mask[p][q]==128)
取出該點samples值(s2)
取出src(fore_Boundary[s2.fi]);src(back_Boundary[s2.bj]);
計算alpha,並根據該alpha求出cost值
if(s1.cost==[]||s1.cost>cost)
更新當前s1中的fi,bj,cost和alpha值
# random search...
for j in range(coords.size()):
I = src[coords[j].x, coords[i].y]
for p in range(k):
F_index = rand()%fore_Boundary.size()
B_index = rand()%back_Boundary.size()
F = src(fore_Boundary[F_index])
B = src(back_Boundary[B_index])
計算出alpha,並根據該alpha求出cost值
if(s1.cost==[]||s1.cost>cost)
更新當前s1中的fi, bj, cost和alpha值
8、for y in range(mask.rows):
for x in range(mask.cols):
if(mask[y][x]==128)
mask[y][x] = 255*samples[y][x].alpha