C# Image Proccessing Techniques: Part III (Substitution of Pixels)


A Digital image is simply a multidimensional array; this array contains numbers which represents the color of points in the image. Therefore, we could easily amend this array easily and do whatever we want with this array. This could include entering this array (Matrix) into a mathematical function for making any amendments in it, or for encrypting the image. Or in this article I will show you a method used in substituting two pixels from two images, for instance you could take a photo for you and place a background of Evil tower behind you. The same technique used in movies, and in the media.

What do we need?

We need to have two images, an image for Evil tower, and a personal image for you with a plain color background (for simplicity). Make sure that the two images have reasonable sizes to substitute them together. In the next articles I will show you different methods of scaling of images.

Now let us move to the steps to write our program.

First you should determine the color components of the background of your picture, please refer to my previous article to see how to get the color component of a point. After that make a nested for loop that traverses over the two images and replace the selected color components of the background, with the color components of the corresponding pixel in the Evil tower image.

Here is the code

Bitmap Pixelssubstitutions(Bitmap PersonalImage, Bitmap EvilImage, Color PlainColor)
        {
            Bitmap NewImage=PersonalImage;
            for(int i=0;i<NewImage.Height;i++)
                for (int j = 0; j < NewImage.Width; j++)
                {
                    Color Pixel=NewImage.GetPixel(j,i);
                    if(Pixel==PlainColor)
                    {
                        NewImage.SetPixel(j,i,EvilImage.GetPixel(j,i));
                    }
                }
 
            return NewImage;
        }

The Output

fig.gif

You can see that some pixels around my body is not replaced with the corresponding Evil tower image, that is because not all plain background pixels have the same exact color components there may be a slight difference, therefore it is better to put a range in the color components selected pixel.

In the next article we will discuss several techniques of image scaling using C#. Please feel free to contact me if you need anything concerning this topic.

 


Similar Articles