Skip to content

Instantly share code, notes, and snippets.

@MatheusFaria
Created June 3, 2018 02:01
Show Gist options
  • Save MatheusFaria/db0a007b9b1c3528f871fe2b30e463ad to your computer and use it in GitHub Desktop.
Save MatheusFaria/db0a007b9b1c3528f871fe2b30e463ad to your computer and use it in GitHub Desktop.
Unity edge detection using sobel filter naive implementation
Shader "matheusfaria/EdgeDetectionSobel"
{
Properties
{
_MainTex ("Base (RGB)", 2D) = "white" {}
_Threshold ("Threshold", Range(0, 1)) = 1
}
Category
{
Tags {
"Queue"="Transparent"
}
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
float2 _MainTex_TexelSize;
int _Threshold;
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert (appdata_base v)
{
v2f o;
o.pos = UnityObjectToClipPos (v.vertex);
o.uv = TRANSFORM_TEX (v.texcoord, _MainTex);
return o;
}
half4 frag (v2f i) : COLOR
{
float3x3 kernel = {
1, 0, -1,
2, 0, -2,
1, 0, -1
};
float2 edge = (0, 0);
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 1; ++y) {
float sample = tex2D(_MainTex,
float2(
i.uv.x + x * _MainTex_TexelSize.x,
i.uv.y + y * _MainTex_TexelSize.y
)
);
edge += float2(kernel[y + 1][x + 1],
kernel[x + 1][y + 1]) * sample;
}
}
float color = step(length(edge), _Threshold);
return half4(color, color, color, 1.0);
}
ENDCG
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment