- Home /
Add Threshold to Color
Hello,
I'm trying to replace a colour within an image that I have. I have a script that searches through each pixel of an image, searching for White, and replaces it with Black.
It's working fairly okay, the only issue is that the pixel has to be perfectly white (FFFFFF/1,1,1). Is there a way to add a threshold so it also replaces 'near' white pixels too?
This is the code that changes the pixels to black:
for(var p = 0; p < pixels.Length; p++){
if(pixels[p] == c)
pixels[p] = new Color(0,0,0,0);
}
c is the Colour that it is searching for (in this case, it is White).
Thanks.
Answer by jenci1990 · Feb 12, 2015 at 04:14 PM
for (var p = 0; p < pixels.Length; p++) {
float threshold = 0.1f; // this is a +- Threshold
float max = Mathf.Clamp01(c.grayscale + threshold); // this is a max value
float min = Mathf.Clamp01(c.grayscale - threshold); // this is the min value
if (pixels[p].grayscale >= min && pixels[p].grayscale <= max) {
pixels[p] = new Color(0, 0, 0, 0);
}
}
Thanks for your answer, I haven't tested it yet, but can you explain why you're using grayscale? Thanks.
Because it is much simpler than other way. The grayscale is average of the red green and blue value. There are many solution for this, but i think this solves your problem.
(Sorry for my english)