Langsung ke konten utama

CV :: Blob detection with Aforge.net to control a servo through an arduino mega

Blob detection with Aforge.net to control a servo through an arduino mega



Hello, 
I've already tested openCV and found a little difficulties to integrate it in a windows form application, although openCV is a great library it's still lack of this characteristic, well I found another magnificent library not so powerful as openCV but can be easily integrated in a c#.net application, it's Aforge.net

It's much easier to learn this framework if you already have knowledge of image processing.
..So I create this application that reads the images from a cheap web cam and look for a specific color in the image get some values from it(x,y,widht) to control a servo via an arduino mega ADK.

To find the object I used blob detection after filter the image with HSLfilter and the convert it to gray scale so I can use the blob detection algorithm  which works only with Binary or gray images.

after that I send the X values of the object through serial to an arduino, where I map it to control a servo angle.

c# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging.Filters;
using AForge.Imaging;

namespace hslfilterblob
{
    public partial class Form1 : Form
    {
        private FilterInfoCollection videoCaptureDevices;
        private VideoCaptureDevice finalVideo;
        private int minHue = 0, maxHue = 355;
        private float minLum = 0, maxLum = 1, minSat = 0, maxSat = 1;
        private Byte[] buffer = new Byte[1];
        private bool serialok = false;
        private float map = 0f;

        public Form1()
        {
            InitializeComponent();
            videoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            finalVideo = new VideoCaptureDevice(videoCaptureDevices[1].MonikerString);
            finalVideo.NewFrame += new NewFrameEventHandler(Finalvideo_newframe);
            finalVideo.Start();
        }

        void Finalvideo_newframe(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap video = (Bitmap)eventArgs.Frame.Clone();
            Bitmap video2 = (Bitmap)eventArgs.Frame.Clone();
            //Create color filter
            HSLFiltering HslFilter = new HSLFiltering();
            //configre the filter
            HslFilter.Hue = new AForge.IntRange(minHue, maxHue);
            HslFilter.Saturation = new AForge.Range(minSat, maxSat);
            HslFilter.Luminance = new AForge.Range(minLum, maxLum);
            //apply color filter to the image
            HslFilter.ApplyInPlace(video2);
            //create gray filter
            Grayscale grayFilter = new GrayscaleBT709();
            Bitmap grayImage = grayFilter.Apply(video2);
            //display Image
            BlobCounter blobcounter = new BlobCounter();
            blobcounter.MinHeight = 100;
            blobcounter.MinWidth = 100;
            blobcounter.ObjectsOrder = ObjectsOrder.Size;
            //locate blobs
            blobcounter.ProcessImage(grayImage);
            Rectangle[] rects = blobcounter.GetObjectsRectangles();
            //draw rectangle around the biggest blob
            if (rects.Length > 0)
            {
                Rectangle objectRect1 = rects[0];
              
                Graphics g = Graphics.FromImage(video);

                    using (Pen pen = new Pen(Color.Red, 3))
                    {
                        g.DrawRectangle(pen, objectRect1);
                        PointF drawPoin = new PointF(objectRect1.X,objectRect1.Y);
                        int objectX = objectRect1.X + objectRect1.Width / 2 - video.Width / 2;
                        int objectY = video.Height / 2 - (objectRect1.Y + objectRect1.Height / 2);
                        String Blobinformation = "X= "+objectX.ToString()+"\nY= "+objectY.ToString()+"\nSize="+objectRect1.Size.ToString();
                        g.DrawString(Blobinformation, new Font("Arial", 16), new SolidBrush(Color.Blue), drawPoin);
                       
                        if (serialok == true)
                        {
                            int second =0;
                            int offset=300;
                            second = offset - Math.Abs(objectX);
                            map =(float) 0.85 * second;
                            buffer[0] = (byte)Math.Abs((int)map);
                            serialPort1.Write(buffer, 0, 1);
                        }
                    }
                    g.Dispose();
               
            }          
            pictureBox1.Image = video;
            pictureBox2.Image = grayImage;
        }

        private void trackBarMaxHue_Scroll(object sender, EventArgs e)
        {
            maxHue = trackBarMaxHue.Value;
        }

        private void trackBarMinHue_Scroll(object sender, EventArgs e)
        {
            minHue = trackBarMinHue.Value;
        }

        private void trackBarMaxSat_Scroll(object sender, EventArgs e)
        {
            maxSat = trackBarMaxSat.Value / 100F;
        }

        private void trackBarSatMin_Scroll(object sender, EventArgs e)
        {
            minSat = trackBarSatMin.Value / 100F;
        }

        private void trackBarLumMax_Scroll(object sender, EventArgs e)
        {
            maxLum = trackBarLumMax.Value / 100F;
        }

        private void trackBarLumMin_Scroll(object sender, EventArgs e)
        {
            minLum = trackBarSatMin.Value / 100F;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ColorDialog colorDlg = new ColorDialog();
            colorDlg.AnyColor = true;
            colorDlg.SolidColorOnly = false;
            colorDlg.Color = Color.Red;

            if (colorDlg.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = colorDlg.Color.GetHue().ToString();
                textBox2.Text = colorDlg.Color.GetSaturation().ToString();
                textBox3.Text = colorDlg.Color.GetBrightness().ToString();
            }
        }

        private void btnCommunication_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Open();
                btnCommunication.BackColor = Color.Green;
                serialok = true;
            }
            catch (Exception t)
            {
                MessageBox.Show(t.ToString());
            }
        }
    }
}

arduino code:

#include <Servo.h>

Servo servo1;
int inbyte=0;
int i;
void setup(){
  servo1.attach(2);
  Serial.begin(9600);
  Serial.println("Start!");
 
  for(i=0;i<180;i++){
    servo1.write(i);
    delay(15);
  }
  servo1.write(90);
}

void loop(){
  if(Serial.available()>0){
    inbyte=Serial.read();
       
  }
     servo1.write(map(inbyte,0,255,0,180));
     delay(15);
}




Komentar

Postingan populer dari blog ini

CV :: Simple Color Tracking Menggunakan Webcam Dengan Library AForge.NET

Simple Color Tracking Menggunakan Webcam Dengan Library AForge.NET Berikut installer demo software simple color tracking. http://www.mediafire.com/file/304priwevhameq0/simple%20color%20tracking.rar Schematic dan firmware http://www.mediafire.com/file/mqdrsjj3qoc7777/Color_Tracking-wangready.wordpress.com.rar Beberapa waktu lalu saat sempat terpikir untuk membuat aplikasi image processing, saya menemukan sebuah library yang saya kira cukup simple untuk diimplementasikan yaitu  AForge.NET  untuk bahasa C#. Alhamdulillah saat itu ada beberapa perangkat yang tersedia di laboratorium sehigga bisa terealisasi. Berikut uraian saya. Simple Color Tracking Abstraksi Robotics vision adalah salah satu bidang kajian dalam dunia robotika. Salah satu langkah awal untuk memulainya adalah robot mampu mengenali warna. Dalam kesempatan kali ini, robot didisain mampu mengenali warna lalu mengikuti gerak dari warna yang terdeteksi tersebut. Sebagai sensornya digunakan ...

CV :: Color Detection & Object Tracking

Color Detection & Object Tracking Object detection and  segmentation  is the most important and challenging fundamental task of computer vision .   It is a critical part in many applications such as image search, scene understanding, etc. However it is still an open problem due to the variety and complexity of object classes and backgrounds. The easiest way to detect and segment an object from an image is the color based methods . The object and the background should have a significant color difference in order to  successfully    segment objects  using color based methods . Simple Example of Detecting a Red Object In this example, I am going to process a video with a red color object and create a binary video by thresholding the red color. (Red color area of the video is  assigned  to '1' and other area is assigned to '0' in the binary image so that you will see a white patch wherever the red object is i...

CV :: Histogram Equalization of Grayscale or Color Image

Histogram Histogram is the intensity distribution of an image. E.G - Consider the following image. Say, depth of the image is 2 bits. Therefore the value range for each and every pixel is from 0 to 3. Sample Image (Depth = 2 bits) Histogram of the a image shows how the pixel values are distributed. As you can see in the above image there are 5 pixels with value 0, 7 pixels with value 1, 9 pixels with value 2 and 4 pixels with value 3. These information is tabulated as follows. Intensity Distribution of above image Histogram of a image usually presented as a graph. The following graph represents the histogram of the above image. Image Histogram Histogram Equalization Histogram Equalization is defined as equalizing the intensity distribution of an image or flattening the intensity distribution curve. Histogram equalization is used to improve the contrast of an image. The equalized histogram of the above image should be ideally like the following graph....