Simple Binarization

Short code snippet to implement the binarization of a graylevel image, using a fixed threshold.

Language:.NET C#/Visual Basic
Version:3.3
Author:IC Imaging Control Support Department

Requirements:
Software:IC Imaging Control 3.3, Visual Studio™ 2010
Hardware:Camera, converter or grabber with WDM Stream Class drivers.
Download C# sampleSimple binarization - C#

The window of the resulting application looks as follows:

The Testdialog of IC Imaging Control,

This brief source code snippet illustrates how to make your own image processing algorithms. The program starts by opening the built-in dialog that the end-user uses to select a video capture device (.ShowDeviceSettingsDialog). At the end of the function Form1_Load(), the live image data stream from the video capture device is displayed, using .LiveStart. .MemoryCurrentGrabberColorformat = ICY8 ensures that the binarization algorithm obtains an 8 bit graylevel image:

C#
      
private void Form1_Load(object sender, System.EventArgs e)
{
    icImagingControl1.ShowDeviceSettingsDialog();

    if( !icImagingControl1.DeviceValid )
    {
        Close();
        return;
    }

    icImagingControl1.MemoryCurrentGrabberColorformat = TIS.Imaging.ICImagingControlColorformats.ICY800;
    icImagingControl1.LiveDisplay = false;
    icImagingControl1.LiveStart();
}

        

When the user clicks "Snap Image", .MemorySnapImage grabs an image from the image data stream and writes it into an internal ring buffer.

C#
      
private void btnSnapImage_Click(object sender, System.EventArgs e)
{
    icImagingControl1.MemorySnapImage();
    icImagingControl1.Display();

    btnBinarize.Enabled = true;
}

        

When the user clicks "Binarize", the program acquires the threshold previously determined by the user (threshold = txtThreshold.Text). Then, it creates the image buffer reference ib and sets it to the ring buffer's current image (ImageBuffers.CurrentIndex). The two for loops that follow, represent the actual image processing algorithm. If the current pixel's graylevel .imageData(x,y) is more than the desired threshold, it is set to 255; otherwise it is set to 0:

C#
      
private void btnBinarize_Click(object sender, System.EventArgs e)
{
    int threshold = int.Parse( txtThreshold.Text );
    if( threshold < 0 || threshold > 255 )
    {
        MessageBox.Show( "Invalid threshold value", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error    );
    }

    TIS.Imaging.ImageBuffer ib = icImagingControl1.ImageActiveBuffer;

    for( int y = 0; y < ib.Lines; ++y )
    {
        for( int x = 0; x < ib.PixelPerLine; ++x )
        {
            if( ib[x,y] < threshold )
                ib[x,y] = 0;
            else
                ib[x,y] = 255;
        }
    }

    icImagingControl1.Display();
}