When transforming colors, Visual Basic .NET represents a color using a vector with 5 entries: red, green, blue, alhpa (opacity), and a scaling value that is 1. A ColorMatrix can transform an image's colors by multiplying each pixel's color vector by a 5-by-5 matrix. An identity matrix, with 1's down the diagonal, leaves all colors unchanged.
The following code uses ColorMatrixes to make three versions of an image with its color components swapped. (To see how this works, multiply the first matrix by the vector (r, g, b, a, 1) and notice that the result is (g, r, b, a, 1) and the red and green components have swapped.)
For each image, the program makes an ImageAttributes object and gives it an appropriate ColorMatrix. It then uses a Graphics object's DrawImage method to copy the original image, passing the ImageAttributes object in to make the color transformation.
The result is probably not terribly useful but it is interesting. The output images almost look colorized.
|
' Display the red, green, and blue component images.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
Dim image_attr As New ImageAttributes
Dim cm As ColorMatrix
Dim rect As Rectangle = _
Rectangle.Round(picSource.Image.GetBounds(GraphicsUnit.Pixel))
Dim wid As Integer = picSource.Image.Width
Dim hgt As Integer = picSource.Image.Height
Dim bm As Bitmap
Dim gr As Graphics
Dim theta As Single
' Swap red/green.
bm = New Bitmap(wid, hgt)
gr = Graphics.FromImage(bm)
theta = PI / 6
cm = New ColorMatrix(New Single()() { _
New Single() {0.0, 1.0, 0.0, 0.0, 0.0}, _
New Single() {1.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 1.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 1.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 0.0, 1.0}})
image_attr.SetColorMatrix(cm)
gr.DrawImage(picSource.Image, rect, 0, 0, wid, hgt, _
GraphicsUnit.Pixel, image_attr)
picRG.Image = bm
' Swap green/blue.
bm = New Bitmap(wid, hgt)
gr = Graphics.FromImage(bm)
theta = PI / 3
cm = New ColorMatrix(New Single()() { _
New Single() {1.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 1.0, 0.0, 0.0}, _
New Single() {0.0, 1.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 1.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 0.0, 1.0}})
image_attr.SetColorMatrix(cm)
gr.DrawImage(picSource.Image, rect, 0, 0, wid, hgt, _
GraphicsUnit.Pixel, image_attr)
picGB.Image = bm
' Swap blue/red.
bm = New Bitmap(wid, hgt)
gr = Graphics.FromImage(bm)
theta = PI / 2
cm = New ColorMatrix(New Single()() { _
New Single() {0.0, 0.0, 1.0, 0.0, 0.0}, _
New Single() {0.0, 1.0, 0.0, 0.0, 0.0}, _
New Single() {1.0, 0.0, 0.0, 0.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 1.0, 0.0}, _
New Single() {0.0, 0.0, 0.0, 0.0, 1.0}})
image_attr.SetColorMatrix(cm)
gr.DrawImage(picSource.Image, rect, 0, 0, wid, hgt, _
GraphicsUnit.Pixel, image_attr)
picBR.Image = bm
End Sub
|