1. Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.
    Dismiss Notice
magvitron

matlab code for detecting and following a red ball.

the code is self explanatory [CODE]clear; clc % Clearing Matlab desktop vid=videoinput('winvide

  1. magvitron
    the code is self explanatory
    Code (text):
    clear;
    clc % Clearing Matlab desktop
    vid=videoinput('winvideo',2,'RGB24_640X480'); % Defining the video input object
    set(vid,'FramesPerTrigger',1); % Setting frames per trigger
    preview(vid); %////// Showing the video of the moving Ball(TO BE USED %
    % WHILE TESTING)
    pause(10);% Waiting for a certain time for the system to get initialised
    rgb_image = getsnapshot(vid); % Storing Image in an array variable
    [a b c]= size(rgb_image); % Determining the size of the captured frame.
    y=a;
    x=b;


    % Defining Boundaries
    x1=x/2-120;
    x2=x/2+120;
    y1=y/2-30;
    y2=y/2+30;
    ser=serial('COM34'); % Defining the specified COM Port to be used
    fopen(ser); % starting serial Communication,opening serial port

    while(1)
    rgb_image = getsnapshot(vid); % storing image in an array variable
    flushdata(vid); %Flushing the buffer
    rbar=0;
    cbar=0;
    e=0;
    fR=rgb_image(:,:,1);fG=rgb_image(:,:,2);fB=rgb_image(:,:,3);% Storing RGB components of the image in seperate arrays
    I=((fR<=70) & (fG>=80) & (fB<=70)); % Converting the RGB Image into binary image///Detecting only the red component
    % Following are the steps For Detecting the red ball
    se=strel('disk',20);
    B=imopen(I,se);
    final=imclose(B,se);
    [L,n]=bwlabel(final);
    %imshow(rgb_image); %////THIS IS TO BE USED ONLY WHILE TESTING
    %hold on % ////THIS IS TO BE USED ONLY WHILE TESTING
    for k=1:n
    [r,c]=find(L==k);
    rbar=mean(r);
    cbar=mean(c);
    %plot(cbar,rbar,'Marker','*','MarkerEdgeColor','B' ,'MarkerSize',20) %////THIS IS TO BE USED ONLY WHILE TESTING
    e=(((cbar>=x1)*2*2*2) + ((cbar<=x2)*2*2) + ((rbar>=y1)*2) + (rbar<=y2)) % Converting to decimal number
    end
    % Decision Making Conditions
    switch (e)
    case 5
    disp('Move left'),fprintf(ser,'L');
    case 6
    disp('Move left'),fprintf(ser,'L');
    case 7
    disp('Move left'),fprintf(ser,'L');
    case 9
    disp('Move right'),fprintf(ser,'R');
    case 10
    disp('Move right'),fprintf(ser,'R');
    case 11
    disp('Move right'),fprintf(ser,'R');
    case 13
    disp('Move forward'),fprintf(ser,'F');
    case 14
    disp('Move back'),fprintf(ser,'B');
    otherwise
    disp('Stop Moving'),fprintf(ser,'S');
    end
    end
    fclose(ser); % closing serial port