I first got inspired to do real-time image processing after looking at this. Here is a small program originally taken from above mentioned link and modified a little for the my own purpose to track a red object using a webcam. This uses Image Aquisition Toolbox and Computer Vision Tollbox to get the image and identify objects. You can also track Blue and Green objects easily by just changing a value. But you need to do a little extra work to identify other colors.
Here are some of the functions you might want to look in Matlab help file if you are getting started.
imaqhwinfo, videoinput, getsnapshot, fliplr, imsubtract, medfilt2, im2bw, bwareaopen, bwlabel, regionprops, imshow, stop, flushdata.
Red Object |
- And here's the source
%Image aquisiton
%Creating video input object
obj = videoinput('winvideo',1,'YUY2_640x480');
% Setting the required properties
set(obj, 'FramesPerTrigger', Inf);
set(obj, 'ReturnedColorspace', 'rgb')
obj.FrameGrabInterval = 2;
%Starting the video aquisition
start(obj)
for k = 1:100
%Current frame
image = getsnapshot(obj);
%Rotating the image left to right since we always get a mirror image
%by doing above mentioned tasks
image(:,:,1) = fliplr(image(:,:,1));
image(:,:,2) = fliplr(image(:,:,2));
image(:,:,3) = fliplr(image(:,:,3));
%Sbtracting the R values from grayscale image to get the Pixels in red
%color
%By using image(:,:,2) or 3 you can track Blue and Green Objects
imgdiff = imsubtract(image(:,:,1), rgb2gray(image));
%Noise filtering
imgdiff = medfilt2(imgdiff, [3 3]);
%Converting into binary image to do the required calculations like
%Centroid of object with some threshold.
imgdiff = im2bw(imgdiff,.25);
%Removing smaller objects
imgdiff = bwareaopen(imgdiff,200);
%Label all the connected components in image
bw = bwlabel(imgdiff, 8);
%Getting the statistics data about the labelled regions
data = regionprops(bw, 'BoundingBox', 'Centroid');
%Show the image
imshow(image)
hold on
%This is a loop to bound the red objects in a rectangular box.
if(~isempty(stats))
xl = length(stats);
for object = 1:xl
bb = stats(object).BoundingBox;
bc = stats(object).Centroid;
rectangle('Position',bb)
plot(bc(1),bc(2), '-m+')
a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), ' Y: ', num2str(round(bc(2)))));
text(10,10,num2str(xl))
set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 12, 'Color', 'yellow');
end
hold off
end
end
% Both the loops end here.
% Stop the video aquisition.
stop(vid);
% Flush all the image data stored in the memory buffer.
flushdata(vid);
%Close all figures
close all
% Clear all variables
clear all
0 comments:
Post a Comment