skiasharpskia

Apply contrast to images using C# and SkiaSharp


I'm trying to apply some image enhancements using C# and SkiaSharp, but the documentation isn't clear. I couldn't find how to apply contrast using SkiaSharp. I'm using Emgu.CV to, but I couldn't find Matrix convolution using Emgu so I'm trying to use only one library.

I'm trying to figure out how to do this (C++) using c# and SkiaSharp

/ Create an SkColorMatrix.

SkColorMatrix matrix;

 

// Modify the contrast. The contrast parameter is a float where:

// 0.0 means the image will be entirely gray.

// 1.0 means the image's original contrast will be preserved.

// Values higher than 1.0 will increase contrast.

float contrast = 1.0f;

matrix.setContrast(contrast);

 

// Create a color filter with the matrix.

sk_sp<SkColorFilter> colorFilter = SkColorFilters::Matrix(matrix);

Solution

  • It's not about matrix but you can apply a color filter, set ColorFilter prop of your SKPaint and draw image with it:

    /// <summary>
    /// Adjusts the contrast of an image. amount is the adjustment level. Negative values decrease contrast, positive values increase contrast, and 0 means no change.
    /// </summary>
    /// <param name="amount"></param>
    /// <returns></returns>
    public static SKColorFilter Contrast(float amount)
    {
        float translatedContrast = amount + 1;
        float averageLuminance = 0.5f * (1 - amount);
    
        return SKColorFilter.CreateColorMatrix(new float[]
        {
            translatedContrast, 0, 0, 0, averageLuminance,
            0, translatedContrast, 0, 0, averageLuminance,
            0, 0, translatedContrast, 0, averageLuminance,
            0, 0, 0, 1, 0
        });
    }