- Home /
calculating
I'm new. try to do some calculations using shaders.
Answer by Jessespike · Mar 27, 2015 at 05:50 PM
I want to count the red pixels in a texture with a shader or do I have to use a computer shader?
I don't think a shader can count the number of pixels in a texture, they don't really work that way. What you can do is write a script to do that for you.
public class CountRedPixels : MonoBehaviour {
// Texture needs Read/Write enabled from the Advanced Texture import settings
public Texture2D _Texture;
[Range(0, 1)]
public float _MinRedColorValue = 0.5f;
// Update is called once per frame
void Update () {
PerformRedPixelCount();
}
void PerformRedPixelCount () {
int numOfRedPixels = 0;
for (int y = 0; y < _Texture.height; y++)
{
for (int x = 0; x < _Texture.width; x++)
{
Color pixelColor = _Texture.GetPixel(x, y);
if (pixelColor.r >= _MinRedColorValue)
{
numOfRedPixels++;
}
}
}
string debugMessage = string.Format("Found {0} pixels in {1} with a minimun R value of {2} ({3})",
numOfRedPixels,
_Texture.name,
_MinRedColorValue,
(int)(_MinRedColorValue * 255));
Debug.Log(debugMessage);
}
}
why can it not work?
Well it's quite complex and I don't fully understand how the shader pipeline operates. But from what I can grasp, pixel (fragment) shaders don't actually handle textures per-pixel, they operate on texels.
I might be wrong and I hope someone will correct me if I am.
In either case, what exactly are you trying to accomplish and why does it have to be done via shader on gpu?
can you remove your answer please ? it doesn't answer my question, I need to do it in shader not in cpu.
Other people can contribute answers as well. I answered your question whether it's possible or not and offered a solution. I won't remove it simply because other knowledge seekers may have the same question in the future, and my solution might help them. You can simply ignore my response and accept someone else's answer.
Your answer
Follow this Question
Related Questions
A Cg shader semantic problem 2 Answers
Help with a see-through shader 0 Answers
How to manipulate a shader's alpha channel while using a texture? 1 Answer
Shader - What is float3.xy? 1 Answer
How to Fade out Custom Unity Shader ? 0 Answers