Created
October 19, 2019 09:57
-
-
Save unitycoder/ecfb256c9112436d59f8b5976e015eb7 to your computer and use it in GitHub Desktop.
Count Pixels in RenderTexture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://forum.unity.com/threads/how-can-i-count-the-number-of-pixels-above-a-threshold-with-a-shader.763232/#post-5084408 | |
| #pragma kernel CSMain | |
| #pragma kernel CSInit | |
| Texture2D<float4> InputImage; | |
| RWStructuredBuffer<int> ResultBuffer; | |
| [numthreads(1, 1, 1)] | |
| void CSInit(uint3 id : SV_DispatchThreadID) | |
| { | |
| ResultBuffer[0] = 0; | |
| } | |
| [numthreads(8, 8, 1)] | |
| void CSMain(uint3 id : SV_DispatchThreadID) | |
| { | |
| uint4 col = InputImage[id.xy]; | |
| if(col.r > 0.4) | |
| { | |
| InterlockedAdd(ResultBuffer[0], 1); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public ComputeShader cShader; | |
| ComputeBuffer cBuffer; | |
| int[] analysisResult; | |
| int kernalMain, kernalInit; | |
| int AnalyseImage() | |
| { | |
| kernalMain = cShader.FindKernel("CSMain"); | |
| kernalInit = cShader.FindKernel("CSInit"); | |
| cBuffer = new ComputeBuffer(1, sizeof(int)); | |
| analysisResult = new int[1]; | |
| cShader.SetTexture(kernalMain, "InputImage", rt); | |
| cShader.SetTexture(kernalInit, "InputImage", rt); | |
| cShader.SetBuffer(kernalMain, "ResultBuffer", cBuffer); | |
| cShader.SetBuffer(kernalInit, "ResultBuffer", cBuffer); | |
| cShader.Dispatch(kernalInit, 1, 1, 1); | |
| cShader.Dispatch(kernalMain, rt.width / 8, rt.height / 8, 1); | |
| cBuffer.GetData(analysisResult); | |
| cBuffer.Release(); | |
| cBuffer = null; | |
| return analysisResult[0]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment