Reputation: 887453
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
Upvotes: 4
Views: 3720
Reputation: 256721
Paul Haeberli
Nov 1993
Four by four matrices are commonly used to transform geometry for 3D rendering. These matrices may also be used to transform RGB colors, to scale RGB colors, and to control hue, saturation and contrast. The most important advantage of using matrices is that any number of color transformations can be composed using standard matrix multiplication.
Please note that for these operations to be correct, we really must operate on linear brightness values. If the input image is in a non-linear brightness space RGB colors must be transformed into a linear space before these matrix operations are used.
RGB colors are transformed by a four by four matrix as shown here:
xformrgb(mat, r, g, b, tr, tg, tb)
float mat[4][4];
float r,g,b;
float *tr,*tg,*tb;
{
*tr = r*mat[0][0] + g*mat[1][0] + b*mat[2][0] + mat[3][0];
*tg = r*mat[0][1] + g*mat[1][1] + b*mat[2][1] + mat[3][1];
*tb = r*mat[0][2] + g*mat[1][2] + b*mat[2][2] + mat[3][2];
}
This is the identity matrix:
float mat[4][4] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
};
Transforming colors by the identity matrix will leave them unchanged.
To scale RGB colors a matrix like this is used:
float mat[4][4] = {
rscale, 0.0, 0.0, 0.0,
0.0, gscale, 0.0, 0.0,
0.0, 0.0, bscale, 0.0,
0.0, 0.0, 0.0, 1.0,
};
Where rscale
, gscale
, and bscale
specify how much to scale the r, g, and b components of colors. This can be used to alter the color balance of an image.
In effect, this calculates:
tr = r*rscale;
tg = g*gscale;
tb = b*bscale;
To convert a color image into a black and white image, this matrix is used:
float mat[4][4] = {
rwgt, rwgt, rwgt, 0.0,
gwgt, gwgt, gwgt, 0.0,
bwgt, bwgt, bwgt, 0.0,
0.0, 0.0, 0.0, 1.0,
};
Where
This is the luminance vector. Notice here that we do not use the standard NTSC weights of 0.299, 0.587, and 0.114. The NTSC weights are only applicable to RGB colors in a gamma 2.2 color space. For linear RGB colors the values above are better.
In effect, this calculates:
tr = r*rwgt + g*gwgt + b*bwgt;
tg = r*rwgt + g*gwgt + b*bwgt;
tb = r*rwgt + g*gwgt + b*bwgt;
To saturate RGB colors, this matrix is used:
float mat[4][4] = {
a, b, c, 0.0,
d, e, f, 0.0,
g, h, i, 0.0,
0.0, 0.0, 0.0, 1.0,
};
Where the constants are derived from the saturation value s
as shown below:
a = (1.0-s)*rwgt + s;
b = (1.0-s)*rwgt;
c = (1.0-s)*rwgt;
d = (1.0-s)*gwgt;
e = (1.0-s)*gwgt + s;
f = (1.0-s)*gwgt;
g = (1.0-s)*bwgt;
h = (1.0-s)*bwgt;
i = (1.0-s)*bwgt + s;
One nice property of this saturation matrix is that the luminance of input RGB colors is maintained. This matrix can also be used to complement the colors in an image by specifying a saturation value of -1.0.
Notice that when s is set to 0.0, the matrix is exactly the "convert to luminance" matrix described above. When s is set to 1.0 the matrix becomes the identity. All saturation matrices can be derived by interpolating between or extrapolating beyond these two matrices.
This is discussed in more detail in the note on Image Processing By Interpolation and Extrapolation.
To offset the r, g, and b components of colors in an image this matrix is used:
float mat[4][4] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
roffset,goffset,boffset,1.0,
};
This can be used along with color scaling to alter the contrast of RGB images.
To rotate the hue, we perform a 3D rotation of RGB colors about the diagonal vector [1.0 1.0 1.0]. The transformation matrix is derived as shown here:
If we have functions:
identmat(mat)
: that creates an identity matrix.xrotatemat(mat,rsin,rcos)
: that multiplies a matrix that rotates about the x (red) axis.yrotatemat(mat,rsin,rcos)
: that multiplies a matrix that rotates about the y (green) axis.zrotatemat(mat,rsin,rcos)
: that multiplies a matrix that rotates about the z (blue) axis.Then a matrix that rotates about the 1.0,1.0,1.0 diagonal can be constructed like this:
First we make an identity matrix
identmat(mat);
Rotate the grey vector into positive Z
mag = sqrt(2.0);
xrs = 1.0/mag;
xrc = 1.0/mag;
xrotatemat(mat, xrs, xrc);
mag = sqrt(3.0);
yrs = -1.0/mag;
yrc = sqrt(2.0)/mag;
yrotatemat(mat, yrs, yrc);
Rotate the hue
zrs = sin(rot*PI/180.0);
zrc = cos(rot*PI/180.0);
zrotatemat(mat, zrs, zrc);
Rotate the grey vector back into place
yrotatemat(mat, -yrs, yrc);
xrotatemat(mat, -xrs, xrc);
The resulting matrix will rotate the hue of the input RGB colors. A rotation of 120.0 degrees will exactly map Red into Green, Green into Blue and Blue into Red. This transformation has one problem, however, the luminance of the input colors is not preserved. This can be fixed with the following refinement:
We make an identity matrix
identmat(mmat);
Rotate the grey vector into positive Z
mag = sqrt(2.0);
xrs = 1.0/mag;
xrc = 1.0/mag;
xrotatemat(mmat, xrs, xrc);
mag = sqrt(3.0);
yrs = -1.0/mag;
yrc = sqrt(2.0)/mag;
yrotatemat(mmat, yrs, yrc);
matrixmult(mmat, mat, mat);
Shear the space to make the luminance plane horizontal
xformrgb(mmat,rwgt,gwgt,bwgt,&lx;,&ly;,&lz;);
zsx = lx/lz;
zsy = ly/lz;
zshearmat(mat,zsx,zsy);
Rotate the hue
zrs = sin(rot*PI/180.0);
zrc = cos(rot*PI/180.0);
zrotatemat(mat,zrs,zrc);
Unshear the space to put the luminance plane back
zshearmat(mat,-zsx,-zsy);
Rotate the grey vector back into place
yrotatemat(mat, -yrs, yrc);
xrotatemat(mat, -xrs, xrc);
I've presented several matrix transformations that may be applied to RGB colors. Each color transformation is represented by a 4 by 4 matrix, similar to matrices commonly used to transform 3D geometry.
These transformations allow us to adjust image contrast, brightness, hue and saturation individually. In addition, color matrix transformations concatenate in a way similar to geometric transformations. Any sequence of operations can be combined into a single matrix using matrix multiplication.
Upvotes: 3
Reputation: 1765
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
);
}
Upvotes: 1
Reputation: 256721
The following code constructs a ColorMatrix
for applying a hue shift.
The insight i had was that at 60° shift in hue space:
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:
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.
Upvotes: 1
Reputation: 6981
This is an old question but solutions posted are much more complicated than the simple answer I found.
Simple:
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
.
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
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!
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.
Upvotes: 1
Reputation: 887453
I ended up porting QColorMatrix to C# and using its RotateHue
method.
Upvotes: 3
Reputation: 144112
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;
}
Upvotes: 4
Reputation: 137148
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.
Upvotes: 2