Click here to Skip to main content
Email Password   helpLost your password?

Introduction  

This is an easy algorithm of image transformation from grayscale image to color. It's far from ideal, but it is very simple.

Background

Usually we calculate gray color as:

Gray  = Green * 0.59 + Blue * 0.30 + Red * 0.11;

Each color with structure [Gray, Gray, Gray] has a set of colors:

G = [Gray, Gray, Gray]
G -> P = {C}, for each C from P: Green * 0.59 + Blue * 0.30 + Red * 0.11 = Gray.

First of all, we create a set of control points. Control point is equivalent of "gray" color and "full" color. When we have control points set, we can approximate any "gray" color to "full" color. If "gray" color is located between two control points C1 and C2, then the color approximates as:

K = (Gray - C1Gray)/(C2Gray - C1Gray)
Red = C1Red + K*(C2Red - C1Red)
Green = C1Green + K*(C2Green - C1Green)
Blue = C1Blue + K*(C2.Blue - C1Blue)

Now we has "full color" equivalent for each "gray" color.

scheme_2.jpg

Figure 1. Transformation schema.

Using the Code  

ControlPoint is a structure for storing data about control points.

public struct ControlPoint
{
    private int level;
     public int Level
    {
        get { return level; }
        set { level = value; }
    }
    private Color color;
     public Color Color
    {
        get { return color; }
        set { color = value; }
    }
     public ControlPoint(int level, Color color)
    {
        this.color = color;
        this.level = level;
    }
     public override string ToString()
    {
        return "Level: " + level.ToString() + "; Color: " + color.ToString();
    }
} 

PointsComparer is a class for comparing two control points:

public class PointsComparer: IComparer<ControlPoint>
{
    #region IComparer<ControlPoint> Members
     public int Compare(ControlPoint x, ControlPoint y)
    {
        if (x.Level > y.Level)
        {
            return 1;
        }
        if (x.Level < y.Level)
        {
            return -1;
        }
        return 0;
    }
     #endregion
} 

ColorBuilder is a class for building a color diagram. It returns an array of 256 colors - our diagram.

public static Color[] GetColorDiagram(List<ControlPoint> points)
{
    Color[] colors = new Color[256];
    points.Sort(new PointsComparer());
     for (int i = 0; i < 256; i++)
    {
        ControlPoint leftColor = new ControlPoint
				(0, GetNearestLeftColor(points[0].Color)); 
        ControlPoint rightColor = new ControlPoint
			(255, GetNearestRigthColor(points[points.Count - 1].Color));
        if (i < points[0].Level)
        {
            rightColor = points[0];
        }
        if (i > points[points.Count - 1].Level)
        {
            leftColor = points[points.Count - 1];
        }
        else
        {
            for (int j = 0; j < points.Count - 1; j++)
            {
                if ((points[j].Level <= i) & (points[j + 1].Level > i))
                {
                    leftColor = points[j];
                    rightColor = points[j + 1];
                }
            }
        }
        if ((rightColor.Level - leftColor.Level) != 0)
        {
            double koef = (double)(i - leftColor.Level) / 
			(double)(rightColor.Level - leftColor.Level);
            int r = leftColor.Color.R + (int)(koef * 
			(rightColor.Color.R - leftColor.Color.R));
            int g = leftColor.Color.G + (int)(koef * 
			(rightColor.Color.G - leftColor.Color.G));
            int b = leftColor.Color.B + (int)(koef * 
			(rightColor.Color.B - leftColor.Color.B));
            colors[i] = Color.FromArgb(r, g, b);
        }
        else
        {
            colors[i] = leftColor.Color;
        }
     }
     return colors;
} 

Now we can get the color image:

colorBitmap = new Bitmap(sourceBitmap);
for (int i = 0; i < sourceBitmap.Width; i++)
{
    for (int j = 0; j < sourceBitmap.Height; j++)
    {
        int level = sourceBitmap.GetPixel(i, j).B;
        colorBitmap.SetPixel(i, j, colors[level]);
    }
}
pbxColorImage.Image = colorBitmap;

ColorDialog.JPG

Figure 2. Simple color dialog.

GrayColor.JPG

Figure 3. Grayscale image, color image and color diagram.

Points of Interest  

The algorithms is very easy, and has many defects. But it is a good example for beginners in image processing. 

Update Information

  1. New formula for grayscale level calculation
  2. Bug with empty list was removed
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalgrayscale to color on HSI model
thanh_rio
1:28 27 Jun '09  
can you write some codes about transforming gray image to color image on HSI model?
thank you for that software!
GeneralRe: grayscale to color on HSI model
Maxim_Barsuk
20:16 28 Jun '09  
Oh... This is a new problem for me. I will try Smile
GeneralCouldnt you make it better???
gonzospy
7:26 1 May '09  
This program obviously substitutes shades of gray for specific colors. After hours of experimenting (yes I was that bored and had that much time on my hands) Ive found that the more control points you can name accurately, the better the fidelity of the produced image. I have been playing with making a bitmapped spectrum on Windows paint program and then reproducing it with the colorizer, and have come very close to producing a true color image. The only problem is I always end up making a mistake when defining the colors manually and then I cant correct that mistake, and I have to start over. Isnt that a problem that could easily be fixed? Or better yet, couldnt someone design the program to automatically assign color values along a set spectrum? That could produce a true image every time, right?
GeneralRe: Couldnt you make it better???
Maxim_Barsuk
20:45 3 May '09  
Yes, you're right. This is not a difficult problem. I will try to correct)
GeneralRe: Couldnt you make it better???
gonzospy
19:25 5 May '09  
thank you Big Grin I didnt really expect a response.... Poke tongue
GeneralRe: Couldnt you make it better??? [modified]
Maxim_Barsuk
20:08 6 May '09  
Hello! Source code is updating. New features: delete control points, settings of grayscale transformation, new color_level_dialog (spectral), save control points to xml and load from xml. ["Update of control points" is not implemented, Im sorry)))))]

modified on Friday, May 8, 2009 6:50 AM

GeneralКруто
Laserson
21:44 26 Jan '09  
Офигеть...Давно искал такую фичу, Автор - кросавчег Wink . Можно я код вставлю в свое приложение (разумеется все копирайты сохраню)?
GeneralRe: Круто
Maxim_Barsuk
5:53 27 Jan '09  
Без проблем, если что то будет работать не так, или смогу чем нибудь еще помочь - обращайся)
GeneralSomething to go off of....
Skully1022
5:34 26 Jan '09  
In document imaging it is important for companies to store documents that are a small size. Now we all know that color images are huge and shouldn't be stored in an imaging system, especially SharePoint. The huge files could clog up the database back end. What you could do is save these color documents as tiff. Then covert them to gray-scale while storing the Control Points in a Tag on the tiff file. You would have to use tiff because no other documents support tagging. Then when a user views the doc, you could build an app that takes the control point and coverts them back to color for their viewing pleasure. It may not be practical but I think it would make a good article.

I think you've started something cool here but your article lacks presentation quality. I know my articles are not perfect so I rated this a four. It seems that the worst of critics are people who can't write articles themselves. Good luck in the future. Keep that english flowing. Smile
GeneralRe: Something to go off of....
Maxim_Barsuk
7:10 26 Jan '09  
Thanks!)
GeneralRe: Something to go off of....
MicroImaging
8:13 3 Jun '09  
PNG Also Supports Tags, and EXIF also Supports Tags
There are plenty of Open source libraries that implement these features, and I have used these features
to keep patient, Date, and Transformation information associated with the File when I was writing
Medical Image software.
GeneralMy vote of 2
MadZookeeper
3:37 26 Jan '09  
Colors are not realistic, code is poorly written and the author does not appear to have very much knowledge on the subject.
Generalwhat about color to grayscale?
bluish
9:26 24 Jan '09  
this is nice. but what about the other way around? especially for 8bit color dithering?
GeneralRe: what about color to grayscale?
Maxim_Barsuk
20:24 25 Jan '09  
ColorTransformApp.zip - simple application for parametric color-to-grayscale transforming. I'm sorry that I don't have time to better solution of this problem.
GeneralLuminace from RGB
terrymohre
4:22 25 Nov '08  
Often we use this weighted method to get the grayscale
Lum = G * 0.59 + B * 0.30 + R * 0.11;

Terry Mohre
GeneralRe: Luminace from RGB
Maxim_Barsuk
6:55 25 Nov '08  
Thanks. Its more realistic formula.
GeneralMy vote of 1
Christian Wikander
2:59 25 Nov '08  
Lacks basic error messages.
What is the use of the function? Make something useful that we can relate to.
GeneralWhy?
Christian Wikander
2:58 25 Nov '08  
I don't see the use of this. Why not make an example that actually does something?
I also think the it's to difficult to get the program working. A simple error message when there are no points would add so much to the experience.
GeneralBugs
Alexander Yakovlev
2:30 21 Nov '08  
I get an unhandled exception when I click either the "Build color diagram" or "Colorize" menu items.
What do I do wrong? I used the Test.JPG which comes with the ZIP.
GeneralRe: Bugs
Maxim_Barsuk
6:39 21 Nov '08  
Oh, Im sorry.

Step 1. Click on right mouse button on image for create control point.
Step 2. "Build color diagram"
Step 3. "Colorize"

Exception generate when list of control points is empty.
NewsRe: Bugs
thanh_rio
7:55 4 Jun '09  
can you show more specific ?
can you write introduction for this software?
thanks
i can't colored an image perfectly.
GeneralRe: Bugs
Maxim_Barsuk
20:08 4 Jun '09  
thanh_rio wrote:
i can't colored an image perfectly.

Quality color image depends on the number of control points. For the control point should be to choose the most common colors in the image. Building a color chart is the next step. Remember that the transformation of monochrome images in color is not unique. Monochrome color lies in the one-dimensional space, color RGB - in three-dimensional space. This algorithm can't give an ideal result, but in some cases the result may be good.


Last Updated 6 May 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010