Trying to figure out a way to determine the best contrasting color for an areas of a photo. The contrasting color is to be used as the color of some overlaying text.
Using Six Labor ImageSharp, far I've been able to:
myImage = Image.Load(imageStream)
myImage.Mutate(x =>x.Crop(rectangle))
But how do I determine the average/dominate color of this cropped area?
I've seen somewhere that one approach is to resize the cropped area into the size of one pixel. This is easy to do (next step would be: myImage.Mutate(x => x.Resize(1,1))
), but how do I then extract the color of this one pixel then?
As I get this color, I plan on using this approach to calculate the contrasting color.
I've rewritten you answer. This should be a little faster and more accurate and uses the existing API.
private Color GetContrastColorBW(int x, int y, int height, int width, stream photoAsStream)
{
var rect = new Rectangle(x, y, height, width);
using Image<Rgba32> image = Image.Load<Rgba32>(photoAsStream);
// Reduce the color palette to the the dominant color without dithering.
var quantizer = new OctreeQuantizer(false, 1);
image.Mutate( // No need to clone.
img => img.Crop(rect) // Intial crop
.Quantize(quantizer) // Find the dominant color, cheaper and more accurate than resizing.
.Crop(new Rectangle(Point.Empty, new Size(1, 1))) // Crop again so the next command is faster
.BinaryThreshold(.5F, Color.Black, Color.White)); // Threshold to High-Low color. // Threshold to High-Low color, default White/Black
return image[0, 0];
}