Introduction
Using C# and the Aforge library, we can easily detect and extract the pupil from an eye image.
Algorithm
- Step 1 - First take the eye image.
- Step 2 - Make it invert.
- Step 3 - Convert it to gray scale.
- Step 4 - Use binary filter taking threshold value 220.
- Step 5 - Find the biggest object.
- Step 6 - Find that object's center point and height.
- Step 7 - Cut a circle from that point taking radius as 2.5 multiply of height.
Using the Code
The code is quite easy, using the Aforge library invert, grayscale, and threshold filters. First see the full code and then I will describe it.
System.Drawing.Bitmap aq = (Bitmap)pictureBox1.Image; Invert a = new Invert();
aq= a.Apply(aq);
AForge.Imaging.Image.FormatImage(ref aq);
IFilter filter = Grayscale.CommonAlgorithms.BT709;
aq = filter.Apply(aq);
Threshold th = new Threshold(220);
aq = th.Apply(aq);
BlobCounter bl = new BlobCounter(aq);
int i = bl.ObjectsCount;
ExtractBiggestBlob fil2 = new ExtractBiggestBlob();
int x = 0;
int y = 0;
int h = 0;
if (i > 0)
{
fil2.Apply(aq);
x = fil2.BlobPosition.X;
y = fil2.BlobPosition.Y;
h = fil2.Apply(aq).Height;
}
System.Drawing.Bitmap Bitmapsource = (Bitmap)pictureBox1.Image;
Rectangle section = new Rectangle(new Point(x - h, y - h), new Size(3 * h, 3 *h));
Bitmap CroppedImage = CropImage(Bitmapsource, section);
pictureBox6.Image = CroppedImage;
First, take the eye image:
System.Drawing.Bitmap aq = (Bitmap)pictureBox1.Image;
Then make it invert:
Invert a = new Invert();
aq= a.Apply(aq);
AForge.Imaging.Image.FormatImage(ref aq);
Now we make it grayscale:
IFilter filter = Grayscale.CommonAlgorithms.BT709;
aq = filter.Apply(aq);
Now we make it binary using threshold 220:
Threshold th = new Threshold(220);
aq = th.Apply(aq);
Now we have to find the biggest object in the binary image:
BlobCounter bl = new BlobCounter(aq);
int i = bl.ObjectsCount;
ExtractBiggestBlob fil2 = new ExtractBiggestBlob();
fil2.Apply(aq);
Next we will find the start position and height of the biggest object/eye pupil:
int x = 0;
int y = 0;
int h = 0;
if (i > 0)
{
fil2.Apply(aq);
x = fil2.BlobPosition.X;
y = fil2.BlobPosition.Y;
h = fil2.Apply(aq).Height;
}
Now we cut the pupil part from the image:
To cut the image, we use the following code:
System.Drawing.Bitmap Bitmapsource = (Bitmap)pictureBox1.Image;
Rectangle section = new Rectangle(new Point(x - h, y - h), new< Size(3 * h, 3 *h));
Bitmap CroppedImage = CropImage(Bitmapsource, section);
The cropped image function code is:
public Bitmap CropImage(Bitmap source, Rectangle section) {
Bitmap bmp = new Bitmap(section.Width, section.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
return bmp;
}
Hope that will help for any eyeball or pupil extraction code.
Points of Interest
For face recognition or detection, eye recognition can be helpful.
History
- 22nd December, 2010: Initial post.