确定照片区域的颜色



试图找出一种方法来确定照片区域的最佳对比度颜色。对比色将用作某些叠加文本的颜色。

使用Six Labor ImageSharp,到目前为止,我已经能够:

  1. 将图像流加载到 Sixlabor ImageSharp 图像中:
    myImage = Image.Load(imageStream)
  2. 使用裁剪进行突变,以划分出文本应位于的大致区域:
    myImage.Mutate(x =>x.Crop(rectangle))

但是如何确定此裁剪区域的平均/主颜色?

我在某处看到一种方法是将裁剪区域的大小调整为一个像素的大小。这很容易做到(下一步是:myImage.Mutate(x => x.Resize(1,1)) (,但是我该如何提取这个像素的颜色呢?

当我得到这种颜色时,我计划使用这种方法来计算对比色。

我已经重写了你的答案。这应该更快、更准确,并使用现有的 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];
}

以下是我最终解决这个问题的方式,使用此算法来确定最佳对比度字体颜色(黑色或白色(。

private Color GetContrastColorBW(int x, int y, int height, int width, stream photoAsStream)
{
    var rect = new SixLabors.Primitives.Rectangle(x,y, height, width);
    var sizeOfOne = new SixLabors.Primitives.Size(1,1);
    using var image = Image.Load<Rgba32>(photoAsStream);
    var croppedImageResizedToOnePixel = image.Clone(
        img => img.Crop(rect)
        .Resize(sizeOfOne));
    var averageColor = croppedImageResizedToOnePixel[0, 0];
    var luminance = (0.299 * averageColor.R + 0.587 * averageColor.G + 0.114 * averageColor.B) / 255;
    return luminance > 0.5 ? Color.Black : Color.White;
}

最新更新