Rotate Hue using ImageAttributes in C#

我只是一个虾纸丫 提交于 2019-12-10 23:27:57

问题


How can I rotate the hue of an image using GDI+'s ImageAttributes (and presumably ColorMatrix)?

Note that I want to rotate the hue, not tint the image.

EDIT: By rotating the hue, I mean that each color in the image should be shifted to a different color, as opposed to making the entire image a shade of one color.

For example,

Original:http://www.codeguru.com/img/legacy/gdi/Tinter03.jpg

Rotated: http://www.codeguru.com/img/legacy/gdi/Tinter15.jpg or http://www.codeguru.com/img/legacy/gdi/Tinter17.jpg


回答1:


I threw this together for this question (ZIP file with c# project linked at the bottom of the post). It does not use ImageAttributes or ColorMatrix, but it rotates the hue as you've described:

//rotate hue for a pixel
private Color CalculateHueChange(Color oldColor, float hue)
{
    HLSRGB color = new HLSRGB(
        Convert.ToByte(oldColor.R),
        Convert.ToByte(oldColor.G),
        Convert.ToByte(oldColor.B));

    float startHue = color.Hue;
    color.Hue = startHue + hue;
    return color.Color;
}



回答2:


I ended up porting QColorMatrix to C# and using its RotateHue method.




回答3:


Have you seen this article on CodeProject?

From an admittedly quick look at the page it looks like 4D maths. You can adopt a similar approach to contstructing matrices as you would for 2D or 3D maths.

Take a series of source "points" - in this case you'll need 4 - and the corresponding target "points" and generate a matrix. This can then be applied to any "point".

To do this in 2D (from memory so I could have made a complete howler in this):

Source points are (1, 0) and (0, 1). The targets are (0, -1) and (1,0). The matrix you need is:

(0, -1, 0)
(1,  0, 0)
(0,  0, 1)

Where the extra information is for the "w" value of the coordinate.

Extend this up to {R, G, B, A, w} and you'll have a matrix. Take 4 colours Red (1, 0, 0, 0, w), Green (0, 1, 0, 0, w), Blue (0, 0, 1, 0, w) and Transparent (0, 0, 0, 1, w). Work out what colours they map to in the new scheme and build up your matrix as follows:

(R1, G1, B1, A1, 0)
(R2, G2, B2, A2, 0)
(R3, G3, B3, A3, 0)
(R4, G4, B4, A4, 0)
(0,   0,   0,   0,   1)

NOTE: The order you do you mulitplication (vector * matrix or matrix * vector) will determine whether the transformed points go vertically or horizontally into this matrix, as matrix multiplication is non-commutative. I'm assuming vector * matrix.




回答4:


This is an old question but solutions posted are much more complicated than the simple answer I found.

Simple:

  • no external dependency
  • no complicated calculation (no figuring out a rotation angle, no applying some cosinus formula)
  • actually does a rotation of colors!

Restating the problem: what do we need ?

I prepared icons tinted red. Some areas are transparent, some are more or less saturated, but they all have red hue. I think it matches your use case very well. The images may have other colors, they will just be rotated.

How to represent the tint to apply ? The simplest answer is: supply a Color.

Working towards a solution

ColorMatrix represent a linear transformation.

Obviously when Color is red, the transformation should be identity. When color is green, the transformation should map red to green, green to blue, blue to red.

A ColorMatrix that does this is :

0 1 0 0 0
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 0 1

Mathematical solution

The "Aha" trick is to recognize that the actual form of the matrix is

R G B 0 0
B R G 0 0
G B R 0 0
0 0 0 1 0
0 0 0 0 1

where R, G and B are simply the component of the tinting color!

Sample code

I took example code on https://code.msdn.microsoft.com/ColorMatrix-Image-Filters-f6ed20ae .

I adjusted it and actually use this in my project:

static class IconTinter
{
    internal static Bitmap TintedIcon(Image sourceImage, Color tintingColor)
    {
        // Following https://code.msdn.microsoft.com/ColorMatrix-Image-Filters-f6ed20ae
        Bitmap bmp32BppDest = new Bitmap(sourceImage.Width, sourceImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        float cr = tintingColor.R / 255.0f;
        float cg = tintingColor.G / 255.0f;
        float cb = tintingColor.B / 255.0f;

        // See [Rotate Hue using ImageAttributes in C#](http://stackoverflow.com/a/26573948/1429390)
        ColorMatrix colorMatrix = new ColorMatrix(
            new float[][]
                       {new float[] { cr,  cg,  cb,  0,  0}, 
                        new float[] { cb,  cr,  cg,  0,  0}, 
                        new float[] { cg,  cb,  cr,  0,  0}, 
                        new float[] {  0,   0,   0,  1,  0}, 
                        new float[] {  0,   0,   0,  0,  1}
                       }
                       );

        using (Graphics graphics = Graphics.FromImage(bmp32BppDest))
        {
            ImageAttributes bmpAttributes = new ImageAttributes();
            bmpAttributes.SetColorMatrix(colorMatrix);

            graphics.DrawImage(sourceImage,
                new Rectangle(0, 0, sourceImage.Width, sourceImage.Height),
                0, 0,
                sourceImage.Width, sourceImage.Height,
                GraphicsUnit.Pixel, bmpAttributes);

        }

        return bmp32BppDest;
    }
}

Hope this helps.

Limitation

  • Notice that the transformation may saturate if you use too bright colors. To guarantee no saturation, tt is sufficient that R+G+B<=1.
  • You may normalize the transformation by dividing cr, cg, cb by cr+cg+cb but handle the case where tinting color is black or you'll divide by zero.



回答5:


The following code constructs a ColorMatrix for applying a hue shift.

The insight i had was that at 60° shift in hue space:

  • red --> green
  • green --> blue
  • blue --> red

is actually a 45° shift in RGB space:

So you can turn some fraction of a 120° shift into some fraction of a 90° shift.

The HueShift parameter must be a value between -1..1.

For example, in order to apply a 60° shift:

  • changing red to yellow,
  • changing yellow to green
  • changing green to cyan
  • changing cyan to blue
  • changing blue to magenta
  • changing magenta to red

you call:

var cm = GetHueShiftColorMatrix(60/360); //a value between 0..1

Implementation:

function GetHueShiftColorMatrix(HueShift: Real): TColorMatrix;
var
    theta: Real;
    c, s: Real;
const
    wedge = 120/360;
begin
    if HueShift > 1 then
        HueShift := 0
    else if HueShift < -1 then
        HueShift := 0
    else if Hueshift < 0 then
        HueShift := 1-HueShift;

    if (HueShift >= 0) and (HueShift <= wedge) then
    begin
        //Red..Green
        theta := HueShift / wedge*(pi/2);
        c := cos(theta);
        s := sin(theta);

        cm[0, 0] :=  c; cm[0, 1] :=  0; cm[0, 2] :=  s; cm[0, 3] :=  0; cm[0, 4] := 0;
        cm[1, 0] :=  s; cm[1, 1] :=  c; cm[1, 2] :=  0; cm[1, 3] :=  0; cm[1, 4] := 0;
        cm[2, 0] :=  0; cm[2, 1] :=  s; cm[2, 2] :=  c; cm[2, 3] :=  0; cm[2, 4] := 0;
        cm[3, 0] :=  0; cm[3, 1] :=  0; cm[3, 2] :=  0; cm[3, 3] :=  1; cm[3, 4] := 0;
        cm[4, 0] :=  0; cm[4, 1] :=  0; cm[4, 2] :=  0; cm[4, 3] :=  0; cm[4, 4] := 1;
    end
    else if (HueShift >= wedge) and (HueShift <= (2*wedge)) then
    begin
        //Green..Blue
        theta := (HueShift-wedge) / wedge*(pi/2);
        c := cos(theta);
        s := sin(theta);

        cm[0, 0] :=  0; cm[0, 1] :=  s; cm[0, 2] :=  c; cm[0, 3] :=  0; cm[0, 4] := 0;
        cm[1, 0] :=  c; cm[1, 1] :=  0; cm[1, 2] :=  s; cm[1, 3] :=  0; cm[1, 4] := 0;
        cm[2, 0] :=  s; cm[2, 1] :=  c; cm[2, 2] :=  0; cm[2, 3] :=  0; cm[2, 4] := 0;
        cm[3, 0] :=  0; cm[3, 1] :=  0; cm[3, 2] :=  0; cm[3, 3] :=  1; cm[3, 4] := 0;
        cm[4, 0] :=  0; cm[4, 1] :=  0; cm[4, 2] :=  0; cm[4, 3] :=  0; cm[4, 4] := 1;
    end
    else
    begin
        //Blue..Red
        theta := (HueShift-2*wedge) / wedge*(pi/2);
        c := cos(theta);
        s := sin(theta);

        cm[0, 0] :=  s; cm[0, 1] :=  c; cm[0, 2] :=  0; cm[0, 3] :=  0; cm[0, 4] := 0;
        cm[1, 0] :=  0; cm[1, 1] :=  s; cm[1, 2] :=  c; cm[1, 3] :=  0; cm[1, 4] := 0;
        cm[2, 0] :=  c; cm[2, 1] :=  0; cm[2, 2] :=  s; cm[2, 3] :=  0; cm[2, 4] := 0;
        cm[3, 0] :=  0; cm[3, 1] :=  0; cm[3, 2] :=  0; cm[3, 3] :=  1; cm[3, 4] := 0;
        cm[4, 0] :=  0; cm[4, 1] :=  0; cm[4, 2] :=  0; cm[4, 3] :=  0; cm[4, 4] := 1;
    end;

    Result := cm;
end;

Note: Any code is released into the public domain. No attribution required.




回答6:


I suppose that www.aforgenet.com could help




回答7:


I build a method that implement @IanBoid code in c# language.

    public void setHueRotate(Bitmap bmpElement, float value) {

        const float wedge = 120f / 360;

        var hueDegree = -value % 1;
        if (hueDegree < 0) hueDegree += 1;

        var matrix = new float[5][];

        if (hueDegree <= wedge)
        {
            //Red..Green
            var theta = hueDegree / wedge * (Math.PI / 2);
            var c = (float)Math.Cos(theta);
            var s = (float)Math.Sin(theta);

            matrix[0] = new float[] { c, 0, s, 0, 0 };
            matrix[1] = new float[] { s, c, 0, 0, 0 };
            matrix[2] = new float[] { 0, s, c, 0, 0 };
            matrix[3] = new float[] { 0, 0, 0, 1, 0 };
            matrix[4] = new float[] { 0, 0, 0, 0, 1 };

        } else if (hueDegree <= wedge * 2)
        {
            //Green..Blue
            var theta = (hueDegree - wedge) / wedge * (Math.PI / 2);
            var c = (float) Math.Cos(theta);
            var s = (float) Math.Sin(theta);

            matrix[0] = new float[] {0, s, c, 0, 0};
            matrix[1] = new float[] {c, 0, s, 0, 0};
            matrix[2] = new float[] {s, c, 0, 0, 0};
            matrix[3] = new float[] {0, 0, 0, 1, 0};
            matrix[4] = new float[] {0, 0, 0, 0, 1};

        }
        else
        {
            //Blue..Red
            var theta = (hueDegree - 2 * wedge) / wedge * (Math.PI / 2);
            var c = (float)Math.Cos(theta);
            var s = (float)Math.Sin(theta);

            matrix[0] = new float[] {s, c, 0, 0, 0};
            matrix[1] = new float[] {0, s, c, 0, 0};
            matrix[2] = new float[] {c, 0, s, 0, 0};
            matrix[3] = new float[] {0, 0, 0, 1, 0};
            matrix[4] = new float[] {0, 0, 0, 0, 1};
        }

        Bitmap originalImage = bmpElement;

        var imageAttributes = new ImageAttributes();
        imageAttributes.ClearColorMatrix();
        imageAttributes.SetColorMatrix(new ColorMatrix(matrix), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

        grpElement.DrawImage(
            originalImage, elementArea,
            0, 0, originalImage.Width, originalImage.Height,
            GraphicsUnit.Pixel, imageAttributes
            );
    }


来源:https://stackoverflow.com/questions/1079820/rotate-hue-using-imageattributes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!