空間域影像處理 在空間域影像處理中, 通常都是基於模板的演算法. 即通過當前像素周圍像素的顏色值來決定當前像素的顏色值. 下面舉例說明:
1. 模糊一目瞭然, 就是把當前像素的顏色用上下左右4個像素的顏色值的和的平均值來代替, 這樣就模糊了….那麼, 怎麼用RenderMonkey來實現呢?從前邊我們知道, 可以用texCoord.x, texCoord.y來表示像素的座標, 然後用tex2D()函數來尋找映像中指定座標的顏色值. 不過要注意, 座標的單位不是像素, 而是紋理坐票, 每個像素對應這裡的映像寬度或高度的倒數. 所以, 我們先引入這兩個值:加入完畢後, 左邊顯示兩個float值 好了, 這樣一來, Color=(S1+S2+S3+S4)/4中的S1的顏色值就可以這樣取到:
| float4 colorS1 = tex2D( Texture0, texCoord + float2(0,-fInverseViewportWidth) ); |
為了計算方便, 我們把模板定義成一個濾波器數組:
| const float4 samples[4] = {-1.0, 0.0, 0, 0.25,1.0, 0.0, 0, 0.25,0.0, .0, 0, 0.25,0.0 -1.0, 0, 0.25}; |
這樣顏色的計算就可以通過一個for迴圈來玩成:
| for(int i = 0; i < 4; i++) { texColor += samples[i].w * tex2D( Texture0, TexCoord + float2(samples[i].x*fInverseViewportWidth, samples[i].y*fInverseViewportHeight) ); } |
效果:以下是整個PixelShader的代碼:
| sampler Texture0; //源映像float fInverseViewportWidth; //寬度的倒數float fInverseViewportHeight; //高度的倒數const float4 samples[4] = { //濾波器 -1, 0, 0, 0.25, 1, 0, 0, 0.25, 0, 1, 0, 0.25, 0,-1, 0, 0.25}; float4 ps_main(float2 TexCoord : TEXCOORD0 ) : COLOR0{ float4 texColor = (float4)0; //初始化顏色值 for(int i = 0; i < 4; i++) { texColor += samples[i].w * tex2D( Texture0, TexCoord + float2(samples[i].x*fInverseViewportWidth, samples[i].y*fInverseViewportHeight) ); } return texColor;} |
明白了上面的程式, 那麼其它效果就很好做了.
2. 邊緣檢測和銳利化
| 相似的, 邊緣檢測的濾波器可以這樣寫: const float4 samples[6] = {-1.0, 1.0, 0, 1.0,0.0, 1.0, 0, 2.0,1.0, 1.0, 0, 1.0, -1.0, -1.0, 0, -1.0,0.0, -1.0, 0, -2.0,1.0, -1.0, 0, -1.0}; |
效果: |
| 銳利化濾波器:const float4 samples[5] = {0.0, 0.0, 0, 11.0/3.0,0.0, 1.0, 0, -2.0/3.0,0.0, -1.0, 0, -2.0/3.0,-1.0, 0.0, 0, -2.0/3.0,1.0, 0.0, 0, -2.0/3.0}; |
效果: |
有了這些基礎, 相信一般的影像處理演算法都沒什麼問題了. 如果需要更多的數學函數的支援, 可以參照這裡:Intrinsic Functions (DirectX HLSL):http://msdn2.microsoft.com/en-us/library/bb509611.aspx這篇文章不錯, 同時也推薦一下:Direct3D提高篇:HLSL編程實現PhotoShop濾鏡效果:http://tech.it168.com/n/2007-03-29/200703291522292.shtml