我有以下标准 .net 库方法可以完美地运行,以便将图像的颜色更改为任何其他颜色的单色:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using MathNet.Numerics.LinearAlgebra;
// ...
// matrix to convert image to grayscale
private static readonly Matrix<float> Grayscale = Matrix<float>.Build.SparseOfArray(new[,]
{
{.3f, .3f, .3f, 0, 0},
{.59f, .59f, .59f, 0, 0},
{.11f, .11f, .11f, 0, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 1}
});
// matrix to invert image colour
private static readonly Matrix<float> Invert = Matrix<float>.Build.SparseOfArray(new[,]
{
{-1f, 0, 0, 0, 0},
{0, -1f, 0, 0, 0},
{0, 0, -1f, 0, 0},
{0, 0, 0, 1f, 0},
{1f, 1f, 1f, 0, 1f}
});
private static Bitmap ChangeColor(this Image original, Color newColour)
{
const float max = byte.MaxValue;
Matrix<float> newColourMatrix = Matrix<float>.Build.Diagonal(
new[]
{
newColour.R / max,
newColour.G / max,
newColour.B / max,
newColour.A / max,
1f
});
// convert to grayscale, invert B&W and then apply new colour
Matrix<float> transformMatrix = Grayscale.Multiply(Invert).Multiply(newColourMatrix);
ColorMatrix colorMatrix = new(transformMatrix.ToRowArrays());
ImageAttributes attributes = new();
attributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
Bitmap newBitmap = new(original.Width, original.Height);
using Graphics graphics = Graphics.FromImage(newBitmap);
graphics.DrawImage(original,
new Rectangle(0, 0, original.Width, original.Height),
0,
0,
original.Width,
original.Height,
GraphicsUnit.Pixel,
attributes);
return newBitmap;
}
我一直在玩 Magick.NET,看看是否可以使用该库实现相同的转换(希望代码少得多),但到目前为止还没有成功。
我目前正在做的改造是:
灰度 >>> 图像负片(暗 -> 亮,反之亦然) >>> 应用新颜色
任何人都可以帮忙吗?