边缘检测的原理是利用一些边缘检测算子对图像进行卷积操作。
转载请注明出处:http://www.cnblogs.com/jietian331/p/7232707.html
例如:
代码如下:
using UnityEngine; public class EdgeDetectRenderer : PostEffectRenderer
{
[SerializeField]
Color m_edgeColor; protected override void OnRenderImage(RenderTexture src, RenderTexture dest)
{
base.Mat.SetColor("_EdgeColor", m_edgeColor);
base.OnRenderImage(src, dest);
} protected override string ShaderName
{
get { return "Custom/Edge Detect"; }
}
}
EdgeDetectRenderer
shader如下:
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)' Shader "Custom/Edge Detect"
{
Properties
{
_MainTex("Main Texture", 2D) = "white" {}
_EdgeColor("Edge Color", Color) = (,,,)
} SubShader
{
Pass
{
Cull Off
ZWrite Off
ZTest Always CGPROGRAM
#pragma vertex vert
#pragma fragment frag sampler2D _MainTex;
float4 _MainTex_TexelSize;
uniform fixed4 _EdgeColor; struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
}; struct v2f
{
float4 pos : SV_POSITION;
half2 uv[] : TEXCOORD0;
}; v2f vert(appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(-, );
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(, );
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(, );
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(-, );
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(, );
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(, );
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(-, -);
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(, -);
o.uv[] = v.uv + _MainTex_TexelSize.xy * half2(, -);
return o;
} float luminance(float3 color)
{
return dot(fixed3(0.2125, 0.7154, 0.0721), color);
} half sober(half2 uvs[])
{
half gx[] = { -, , ,
-, , ,
-, , };
half gy[] = { -, -, -,
, , ,
, , }; float edgeX = ;
float edgeY = ; for(int i = ; i < ; i++)
{
fixed3 c = tex2D(_MainTex, uvs[i]).rgb;
float l = luminance(c);
edgeX += l * gx[i];
edgeY += l * gy[i];
} return abs(edgeX) + abs(edgeY);
} fixed4 frag(v2f i) : SV_TARGET
{
half edge = sober(i.uv);
fixed4 tex = tex2D(_MainTex, i.uv[]);
return lerp(tex, _EdgeColor, edge);
} ENDCG
}
} Fallback Off
}
效果如下: