2012-10-03 24 views
3

我想在Photoshop中爲我的iPhone應用程序中的GLSL着色器(從相機捕捉圖像)創建類似「Magic Wand」的效果,以獲得屏幕的中心像素。現在我通過獲取像素數組併爲中心像素應用某種填充算法(全部使用Objective-C代碼)來實現此目的。這是在CPU上執行的,這對我來說有點太慢了,所以我想嘗試使用GLSL着色器。實際上,我所需要的只是重寫片段着色器中的填充填充,更確切地說,要知道當前片段的顏色是否接近閾值顏色,以及當前片段是否爲先前在區域中檢測到的片段的鄰居。這聽起來對我來說太令人困惑,我不明白這是否可能。GLSL:是否可以創建包含中心像素的單色區域的遮罩?

的洪水填充算法是(僞):

Flood-fill (node, target-color, replacement-color): 
1. Set Q to the empty queue. 
2. If the color of node is not equal to target-color, return. 
3. Add node to Q. 
4. For each element n of Q: 
5.  If the color of n is equal to target-color: 
6.   Set w and e equal to n. 
7.   Move w to the west until the color of the node to the west of w no longer matches target-color. 
8.   Move e to the east until the color of the node to the east of e no longer matches target-color. 
9.   Set the color of nodes between w and e to replacement-color. 
10.   For each node n between w and e: 
11.    If the color of the node to the north of n is target-color, add that node to Q. 
12.    If the color of the node to the south of n is target-color, add that node to Q. 
13. Continue looping until Q is exhausted. 
14. Return. 

的問題:是有可能這樣做,在着色器,如果是,我該怎麼辦呢?

謝謝!

回答

3

不,着色器不會那樣工作。在着色器中,您始終只能讀取或寫入,而不能同時寫入。如果你回頭看看你的算法,它會讀取和寫入相同的數據。

你可以嘗試乒乓球方案,但我懷疑它會很快:

for (sometime) 
    for (every pixel in dest) 
    if source has filled neighbours (up,left,top,bottom) and is above threshold, then write fill 
    else write source 
    flip source and dest 

這一步每次迭代的一個像素的更多 - 但你只有當它做了一個上限(在圖片大小)。

你可以更聰明地嘗試做一些金字塔方案:首先以2倍的低分辨率運行,然後用它來確定填充區域。但它實際上不是一種在GPU上運行良好的算法。我建議改爲使用手動優化的彙編CPU版本。

+0

我期待那..我會按照你的意見,並嘗試優化CPU,因爲我不知道如果結果會很好,謝謝你的回答! – medvedNick

+0

Mike Ash在實施和優化洪水填充方面有兩個帖子,可能會對您感興趣:http://www.mikeash.com/pyblog/friday-qa-2012-09-14-implementing-a-flood-fill。 html http://www.mikeash.com/pyblog/friday-qa-2012-09-28-optimizing-flood-fill.html – Pivot

+0

很好的鏈接!謝謝你的加入 - 對不起,我不能贊成評論。但是現在你讓我想到再次發生洪水填充。這樣一個簡單易用的算法。容易得到最壞的情況下測試。真的很難放在GPU上。 – starmole

相關問題