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.

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);
}
}