Sunday, 7 December 2014

detect corners of a face

Iface=imread('fr56.png');
>> faceDetector = vision.CascadeObjectDetector('FrontalFaceCART');
cornerDetector = vision.CornerDetector('Method','Harris corner detection (Harris & Stephens)');
Irgb2gray=rgb2gray(Iface);
bboxes = step(faceDetector, Irgb2gray);
corners = detectHarrisFeatures(Irgb2gray);
Irgb2gray = insertObjectAnnotation(Iface, 'rectangle', bboxes, 'Face');
figure, imshow(Irgb2gray), title('Detected faces'); hold on;
plot(points.selectStrongest(50));

Tuesday, 14 October 2014

How to locate people in an image

%Create a people detector, and load the input image.

   peopleDetector = vision.PeopleDetector;
   I = imread('visionteam1.jpg');
%Detect people using the people detector object.

   [bboxes, scores] = step(peopleDetector, I);
%Create a shape inserter and a score inserter.

   shapeInserter = vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',[255 255 0]);
   
    scoreInserter = vision.TextInserter('Text',' %f','Color', [0 80 255],'LocationSource','Input port','FontSize',16);
%Draw detected bounding boxes, and insert scores using the inserter objects.

    I = step(shapeInserter, I, int32(bboxes));
    I = step(scoreInserter, I, scores, int32(bboxes(:,1:2)));
    figure, imshow(I)
    title('Detected people and detection scores'); 

Tuesday, 30 September 2014

find distance of an image

a=imread('peppers.png');
 bw=im2bw(a);
 d1=bwdist(bw,'euclidean');
imshow(mat2gray(d1));
hold on,imcontour(d1);

Thursday, 28 August 2014

track an object is optical flow

vid = videoinput('winvideo', 1);
% Configure the number of frames to log upon triggering.
set(vid,'FramesPerTrigger', 1);
set(vid,'TriggerRepeat', Inf);
optical = vision.OpticalFlow( ...
    'OutputValue', 'Horizontal and vertical components in complex form');
imsize = get(vid,'VideoResolution');
shapes = vision.ShapeInserter;
shapes.Shape = 'Lines';
shapes.BorderColor = 'white';
row = 1:5:imsize(2);
column = 1:5:imsize(1);
[Cv, Rv] = meshgrid(column,row);
Rv = Rv(:)';
Cv = Cv(:)';
hVideoIn = vision.VideoPlayer;
hVideoIn.Name  = 'Original Video';
hVideoOut = vision.VideoPlayer;
hVideoOut.Name  = 'Motion Detected Video';
% Start the Image Acquisition device.
start(vid);

% Set up for stream
nFrames = 0;
while (nFrames<100)     % Process for the first 100 frames.
    % Acquire single frame of single data type.
    rgbData = getdata(vid, 1, 'single');

    % Compute the optical flow for that particular frame.
    optFlow = step(optical,rgb2gray(rgbData));

    % Downsample optical flow field.
    optFlow_DS = optFlow(row, column);
    H = imag(optFlow_DS)*50;
    V = real(optFlow_DS)*50;

    % Draw lines on top of image
    lines = [Rv; Cv; Rv+H(:)'; Cv+V(:)'];
    rgb_Out = step(shapes, rgbData, lines);

    % Send image data to video player
    % Display original video.
    step(hVideoIn, rgbData);
    % Display video along with motion vectors.
    step(hVideoOut, rgb_Out);

    % Increment frame count
    nFrames = nFrames + 1;

track car using optical flow

hbfr = vision.BinaryFileReader( ...
        'Filename', 'viptraffic.bin');
hcr = vision.ChromaResampler(...
  'Resampling', '4:2:0 (MPEG1) to 4:4:4', ...
  'InterpolationFilter', 'Pixel replication');
hcsc1 = vision.ColorSpaceConverter('Conversion', 'YCbCr to RGB');
hcsc2 = vision.ColorSpaceConverter('Conversion', 'RGB to intensity');
idtc = vision.ImageDataTypeConverter('OutputDataType', 'single');
hof = vision.OpticalFlow( ...
    'OutputValue', 'Horizontal and vertical components in complex form', ...
    'ReferenceFrameDelay', 3);
hmean1 = vision.Mean;
hmean2 = vision.Mean('RunningMean', true);
hmedianfilt = vision.MedianFilter;
hclose = vision.MorphologicalClose('Neighborhood', strel('line',5,45));
hblob = vision.BlobAnalysis( ...
                    'CentroidOutputPort', false, ...
                    'AreaOutputPort', true, ...
                    'BoundingBoxOutputPort', true, ...
                    'OutputDataType', 'double', ...
                    'NumBlobsOutputPort',  false, ...
                    'MinimumBlobAreaSource', 'Property', ...
                    'MinimumBlobArea', 250, ...
                    'MaximumBlobAreaSource', 'Property', ...
                    'MaximumBlobArea', 3600, ...
                    'FillValues', -1, ...
                    'MaximumCount', 80);
herode = vision.MorphologicalErode('Neighborhood', strel('square',2));
hshapeins1 = vision.ShapeInserter( ...
            'BorderColor', 'Custom', ...
            'CustomBorderColor', [0 1 0]);
hshapeins2 = vision.ShapeInserter( ...
            'Shape','Lines', ...
            'BorderColor', 'Custom', ...
            'CustomBorderColor', [255 255 0]);
htextins = vision.TextInserter( ...
        'Text', '%4d', ...
        'Location',  [0 0], ...
        'Color', [1 1 1], ...
        'FontSize', 12);
sz = get(0,'ScreenSize');
pos = [20 sz(4)-300 200 200];
hVideo1 = vision.VideoPlayer('Name','Original Video','Position',pos);
pos(1) = pos(1)+220; % move the next viewer to the right
hVideo2 = vision.VideoPlayer('Name','Motion Vector','Position',pos);
pos(1) = pos(1)+220;
hVideo3 = vision.VideoPlayer('Name','Thresholded Video','Position',pos);
pos(1) = pos(1)+220;
hVideo4 = vision.VideoPlayer('Name','Results','Position',pos);

% Initialize some variables used in plotting motion vectors.
MotionVecGain = 20;
line_row =  22;
borderOffset   = 5;
decimFactorRow = 5;
decimFactorCol = 5;
firstTime = true;

Tuesday, 26 August 2014

Geometric transform on an object

 htrans2 = vision.GeometricTransformer;
 img2 = checker_board(20,10);
 tfMat=[1      0     -15*2     0      1      15*2; ...
        0.4082 0      15*2    -0.4082 1.0204 35*2; ...
        1     -0.4082 5.4082*2 0      0.4082 44.5918*2]';

 polyROI  = [50  0 50 49 99 49 99 0; ...
              0  0  0 49 49 49 49 0; ...
             50 50 50 99 99 99 99 50]' * 2;

 htrans2.BackgroundFillValue = [0.5 0.5 0.75];
 htrans2.ROIInputPort = true;
 htrans2.ROIShape = 'Polygon ROI';
 transimg2 = step(htrans2,img2,tfMat,polyROI);
 imshow(img2);
 figure;imshow(transimg2);

draw circles on an object

I = imread('coins.png');
figure, imshow(I);
position = [96 146 31;236 173 26];
label = [5 10];
RGB = insertObjectAnnotation(I, 'circle', position, label,'Color', {'cyan', 'yellow'}, 'TextColor', 'black');
figure, imshow(RGB), title('Annotated coins');

morphology operations top hat and bottom hat

 I = im2single(imread('rice.png'));
 htop = vision.MorphologicalTopHat('Neighborhood',strel('disk', 12));

% Improve contrast of output image
   hc = vision.ContrastAdjuster;  J = step(htop,I);
  J = step(hc,J);
  figure;

 subplot(1,2,1),imshow(I); title('Original image');
 subplot(1,2,2),imshow(J);
 title('Top-hat filtered image');




I = im2single(b);
 hbot = vision.MorphologicalBottomHat('Neighborhood',strel('disk', 5));
 J = step(hbot,I);
 figure;
 subplot(1,2,1),imshow(I); title('Original image');
 subplot(1,2,2),imshow(J);
 title('Bottom-hat filtered image'); 

Draw a shape over an object

I = imread('board.tif');
figure, imshow(I);
label_str = cell(3,1);
conf_val = [85.212 98.76 78.342]; 
for ii=1:3
    label_str{ii} = ['Confidence: ' num2str(conf_val(ii),'%0.2f') '%'];
end
position = [23 373 60 66;35 185 77 81;77 107 59 26];
RGB = insertObjectAnnotation(I, 'rectangle', position, label_str,'TextBoxOpacity', 0.9, 'FontSize', 18);
figure, imshow(RGB), title('Annotated chips');

morphological operations in matlab

hcsc = vision.ColorSpaceConverter;
 hcsc.Conversion = 'RGB to intensity';
 hautothresh = vision.Autothresholder;
 hdilate = vision.MorphologicalDilate('Neighborhood', ones(5,5));
 x1 = step(hcsc, a);
 x2 = step(hautothresh, x1);
 y = step(hdilate, x2);
 figure;
 subplot(3,1,1),imshow(a); title('Original image');
 subplot(3,1,2),imshow(x2); title('Thresholded Image');
 subplot(3,1,3),imshow(y); title('Dilated Image');

Friday, 18 July 2014

To find transpose of an image

for i=1:512
   for j=1:512
    B(j,i)=A(i,j);
 end
end


Vertical Flip

for i=1:512
   for j=1:512
    B(i,512+1-j)=A(i,j);
 end
end

Image Cropping

for k=0:64-1
    for l=0:128-1
        B(k+1,l+1)=A(255+k+1,255+l+1);
  end
end
 

Thursday, 17 July 2014

detect people in matlab

peopleDetector = vision.PeopleDetector;
I = imread('visionteam1.jpg');
[bboxes, scores] = step(peopleDetector, I);
shapeInserter = vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',[255 255 0]);
 scoreInserter = vision.TextInserter('Text',' %f','Color', [0 80 255],'LocationSource','Input port','FontSize',16);
I = step(shapeInserter, I, int32(bboxes));
 I = step(scoreInserter, I, scores, int32(bboxes(:,1:2)));
figure, imshow(I)
title('Detected people and detection scores'); 

how to detect cars in an image taken from real time

foregroundDetector = vision.ForegroundDetector('NumGaussians', 3, ...
    'NumTrainingFrames', 50);

videoReader = vision.VideoFileReader('visiontraffic.avi');
for i = 1:150
    frame = step(videoReader); % read the next video frame
    foreground = step(foregroundDetector, frame);
end
figure; imshow(frame); title('Video Frame');
figure; imshow(foreground); title('Foreground');
se = strel('square', 3);
filteredForeground = imopen(foreground, se);
figure; imshow(filteredForeground); title('Clean Foreground');
blobAnalysis = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
    'AreaOutputPort', false, 'CentroidOutputPort', false, ...
    'MinimumBlobArea', 150);
bbox = step(blobAnalysis, filteredForeground);
result = insertShape(frame, 'Rectangle', bbox, 'Color', 'green');
numCars = size(bbox, 1);
result = insertText(result, [10 10], numCars, 'BoxOpacity', 1, ...
    'FontSize', 14);
figure; imshow(result); title('Detected Cars');

Wednesday, 16 July 2014

how to reduce image using Gaussian Pyramid Decomposition

The image reduction step involves lowpass filtering and downsampling the image pixels. The image expansion step involves upsampling the image pixels and lowpass filtering.


Example
gaussPyramid = vision.Pyramid('PyramidLevel', 2);
I = im2single(imread('cameraman.tif'));                 
J = step(gaussPyramid, I);
figure, imshow(I); title('Original Image');
figure, imshow(J); title('Reduced Image');

Monday, 14 July 2014

Useful System Objects for Video File I/O, Display, and Graphics

Useful System Objects for Video File I/O,  Display, and Graphics

File I/O
–VideoFileReader
–VideoFileWriter

Display
–VideoPlayer
–DeployableVideoPlayer

Graphics
–AlphaBlender
–MarkerInserter
–ShapeInserter
–TextInserter

Preprocessing
–ChromaResampler
–Deinterlacer
–DemosaicInterpolator

Statistics (running across video frames)
–Histogram
–Maximum
–Mean
–Median
–Minimum
–StandardDeviation
–Variance

how to count number of cells in image

a=imread('normal.jpg');
[m n p]=size(a);
 r=a(:,:,1);
 g=a(:,:,2);
 b=a(:,:,3);
for i=1:m
    for j=1:n
        for k=1:p
        if (r(i,j)>200)||(g(i,j)>160)||(b(i,j)>200)
      d(i,j)=0;
  else
      d(i,j)=a(i,j);
        end
    end
    end
end
imshow(d);
b=imcomplement(d);
figure,imshow(b);
[l num]=bwlabel(b,4);
figure,disp(l);
for i=1:num
    imshow(l==i);
   % pause(1);
 end



roipoly command in matlab

a=imread('data1.jpg');
[m n]=ginput(1);
bw=roipoly(a,m,n);
figure,imshow(bw);
[M N]=size(bw);
for i=1:m
 for j=1:n
    if bw(i,j)==1
       b(i,j)=a(i,j);
   else
      b(i,j)=0;
   end
end
end
figure,imshow(b,[]);title('output image');

Video to frame conversion

clc;
close all;

% Open an
filename = 'vipmen.avi';
mov =VideoReader(filename);
% sample avi file
 % Output folder

outputFolder = fullfile(cd, 'frames');
if ~exist(outputFolder, 'dir')
mkdir(outputFolder);
end

%getting no of frames

numberOfFrames = mov.NumberOfFrames;
numberOfFramesWritten = 0;
for frame = 1 : numberOfFrames
thisFrame = read(mov, frame);
outputBaseFileName = sprintf('%3.3d.png', frame);
outputFullFileName = fullfile(outputFolder, outputBaseFileName);
imwrite(thisFrame, outputFullFileName, 'png');
progressIndication = sprintf('Wrote frame %4d of %d.', frame,numberOfFrames);
disp(progressIndication);
numberOfFramesWritten = numberOfFramesWritten + 1;
end
progressIndication = sprintf('Wrote %d frames to folder "%s"',numberOfFramesWritten, outputFolder);
disp(progressIndication);

Sunday, 13 July 2014

To extract iris region from eye image

It is a program to detect the iris region in an image based on RGB values. The outermost region is eliminated and then the image is as shown


The program to convert the image into binary is as shown:

 a=imread('eye1.jpg');
[m n p]=size(a);
 r=a(:,:,1);
 g=a(:,:,2);
 b=a(:,:,3);
for i=1:m
    for j=1:n
        for k=1:p
        if (r(i,j)>125)||(g(i,j)>75)||(b(i,j)>42)
      d(i,j)=0;
  else
      d(i,j)=a(i,j);
        end
    end
    end
end
d1=uint(d);
figure,imshow(d1);
b=rgb2gray(a);
 figure,imshow(a);
figure,imshow(b);
%figure,imshow(c);
c=im2bw(b,0.3);
i6=medfilt2(c,[3 3]);
figure,imshow(c);
%imtool(i6);
figure,imshow(i6);

How to insert text onto images

The insertion of text can be done on an image by specifying color and location.The input image I, can be a 2-D grayscale image or a truecolor RGB image. The textInserter returns a text inserter object which draws text on image. The step function is used to draw the specified text onto input image

textColor    = [255, 255, 255];
textLocation = [100 315];
a=imread('data1.jpg');
textInserter = vision.TextInserter('Swarupa','Color', textColor, 'FontSize', 24, 'Location', textLocation);
J = step(textInserter, a);
imshow(J);

homomorphic filtering

Homomorphic Filtering 
Homomorphic filtering is a generalized technique for nonlinear image enhancement and correction. It 
simultaneously normalizes the brightness across an image and increases contrast. 

An image can be expressed as the product of illumination and reflectance: 
f( x, y ) = i( x, y )⋅r( x, y ) 

When the illumination is uniform, i( x,y ) is considered to be a constant and the image is considered to 
the reflectance of the object. However, the lighting condition is usually unequal. The illumination component 
tends to vary slowly and its frequency fastens on low part in the frequency domain; the reflectance tends to 
vary rapidly and its frequency is in high part. If two components can be operated separately, the illumination 
problem will be solved and the image will be enhanced. Hence, the log transform is used to equation (1): 
ln f( x, y )= lni( x, y )+lnr( x,y ) -(2) 
Then Fourier transform is used to equation (2), which makes the succedent operation is in frequency 
domain. 

Friday, 11 July 2014

morphology operations

clear all
close all
a=imread('cell1.bmp'); % reads the image
b=im2bw(a); %convert to binary
b1=bwareaopen(b,550); % remove connected components from a binary image
b2=imfill(b1,'holes'); % fill the region
%dialte
se=strel('disk',3,6); %structuring elt default:4
d1=imdilate(b2,se);
%imerode
se1=strel('disk',11);
d2=imerode(d1,se1);
%contour
p=bwmorph(d1,'remove');
perimeter=sum(sum(p));
figure(1);imshow(a);
figure(2);imshow(b1);
figure(3);imshow(d1);
figure(4);imshow(d2);
figure(5);imshow(p);
fprintf('perimeter of the shape');
disp(perimeter)

Wednesday, 9 July 2014

convert image to binary in vision toolbox

 a=imread('untitled1.jpg');
 hcsc = vision.ColorSpaceConverter;
hcsc.Conversion = 'RGB to intensity';
 i2 = step(hcsc, a);
imshow(i2);
 bin = step(hautoth,i2);
figure;imshow(bin);

How to insert a shape on an gray image

yellow = uint8([255 255 0]);
shapeInserter = vision.ShapeInserter('Shape','Circles','BorderColor','Custom','CustomBorderColor',yellow);
I = imread('cameraman.tif');
circles = int32([30 30 20; 80 80 25]);
RGB = repmat(I,[1,1,3]); % convert I to an RGB image
J = step(shapeInserter, RGB, circles);
imshow(J);

Monday, 7 July 2014

Detect Face and track using feature points

videoFileReader = vision.VideoFileReader('visionface.avi');
videoPlayer = vision.VideoPlayer('Position', [100, 100, 680, 520]);
objectFrame = step(videoFileReader);
objectRegion = [264, 122, 93, 93];
objectImage = insertShape(objectFrame, 'Rectangle', objectRegion,'Color', 'red');
figure; imshow(objectImage); title('Yellow box shows object region');
 points = detectMinEigenFeatures(rgb2gray(objectFrame), 'ROI', objectRegion);
 pointImage = insertMarker(objectFrame, points.Location, '+', 'Color', 'white');
figure, imshow(pointImage), title('Detected interest points');
 pointImage = insertMarker(objectFrame, points.Location, '+', 'Color', 'white');
figure, imshow(pointImage), title('Detected interest points');
tracker = vision.PointTracker('MaxBidirectionalError', 1);
 initialize(tracker, points.Location, objectFrame);
 while ~isDone(videoFileReader)
      frame = step(videoFileReader);
      [points, validity] = step(tracker, frame);
      out = insertMarker(frame, points(validity, :), '+');
      step(videoPlayer, out);
end
release(videoPlayer);
release(videoFileReader);

Sunday, 6 July 2014

Skin color detection using YCbCr plane

I=imread('filename');
I=double(I);
[hue,s,v]=rgb2hsv(I);
cb =  0.148* I(:,:,1) - 0.291* I(:,:,2) + 0.439 * I(:,:,3) + 128;
cr =  0.439 * I(:,:,1) - 0.368 * I(:,:,2) -0.071 * I(:,:,3) + 128;
[w h]=size(I(:,:,1));
for i=1:w
    for j=1:h            
        if  140<=cr(i,j) && cr(i,j)<=165 && 140<=cb(i,j) && cb(i,j)<=195 && 0.01<=hue(i,j) && hue(i,j)<=0.1     
            segment(i,j)=1;            
        else       
            segment(i,j)=0;    
        end    
    end
end
% imshow(segment);
im(:,:,1)=I(:,:,1).*segment;   
im(:,:,2)=I(:,:,2).*segment; 
im(:,:,3)=I(:,:,3).*segment; 
figure,imshow(uint8(im));

Friday, 4 July 2014

Segement cells in an image


%% Segmment cells in an image?
% A customer recently provided me with an image of cells that were roughly
% circular, but not very well defined, and often overlapping. He asked how
% we might use MATLAB and the <http://www.mathworks.com/products/image/ Image Processing Toolbox>
% to segment the cells in the presence of noise.
%
% Many of us know the Hough transform functionality in the Image Processing
% Toolbox, and the ability of that function to detect lines in an image.
% With some modifications, the Hough transform can be used to find other
% shapes as well. In this case, I wanted to find circles; a quick search
% for "detect circles" on the MATLAB Central File Exchange revealed
% <http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objectId=1094843&objectType=author Tao Peng>'s
% implementation of the 
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=9168&objectType=FILE Circular Hough Transform>.
% After an easy download, I was on my way to solving the problem. Tao's file is <http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objectType=author&objectId=1093599 Brett>'s
% choice for this week's Pick of the Week.
%
% (Thanks to Cem Girit at Biopticon Corp. for permission to use his image!)

%% Read, Display image
togglefig Original
% Note: togglefig is a utility function I wrote for managing figure
% windows, and is available
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=18220&objectType=file here>.
img = imread('NB1ln1.jpg');
imshow(img);

%% How would you segment this?
% Segmentation is often a very challenging task, particularly with noisy
% images like this one. One might try simple threshold or edge detection
% routines, or more sophisticated watershed approaches, for instance.
% Unfortunately, none of these approaches was giving me the results I
% wanted for this particular image. I was at a bit of a loss--until I found
% CircularHough_Grd. Tao suggests some filtering operations in his very
% helpful comments. For this demonstration, I'm going to see how the
% algorithm can perform with just some very minor pre-processing. 

%% Discarding color information
% Tao's function works directly on grayscale images. Rather than converting
% the color image to grayscale with the Image Processing Toolbox's RGB2GRAY
% function, I elected to  simply use the first (red) color plane, and to
% use adaptive histogram equalization:
togglefig('Red Plane, Adjusted')
red = img(:,:,2);
red = adapthisteq(red);
imshow(red)

%% Parameters for the segmentation
% Before I segment, I needed to know how big the cells were in the image;
% CircularHough_Grd takes as an input a range of radii to search for. Using
% the IMDISTLINE function in the Image Processing Toolbox's IMTOOL, I
% estimated that the radii of interest range from about 5 to 25 pixels. 
%
% You can play around with the other input arguments to modify the
% function's sensitivity to less-than-perfect circles, for instance, or to
% change the way it deals with concentric circles. This makes the program
% pretty flexible!

%% Now for the segmentation...
tic;
[accum, circen, cirrad] = ...
    CircularHough_Grd(red, [5 25],...
    20, 13, 1);
toc

%% ...and a bit of post-processing
% Note to Tao: occasionally, your algorithm returns zero-radii "hits":
any(cirrad <= 0)
%%
% This is easy to address (for instance, to keep the RECTANGLE command below
% from erroring), but might be an opportunity for enhancement.
if any(cirrad <= 0)
    inds = find(cirrad>0);
    cirrad = cirrad(inds);
    circen = circen(inds,:);
end

%% View the results
% Now let's see how well the algorithm performed: 
togglefig Results
imshow(img);
hold on;
plot(circen(:,1), circen(:,2), 'r+');
for ii = 1 : size(circen, 1)
    rectangle('Position',[circen(ii,1) - cirrad(ii), circen(ii,2) - cirrad(ii), 2*cirrad(ii), 2*cirrad(ii)],...
        'Curvature', [1,1], 'edgecolor', 'b', 'linewidth', 1.5);
end
hold off;
%%
% That's pretty remarkable, especially given the simplicity of my
% pre-processing. (Adaptive histogram equilization helped a lot; Tao's
% suggested filters improve the performance even more.)

%% Final comments
% The time it takes to run this algorithm varies markedly, depending on the
% user settings. In this case, it took my computer approximately 4
% seconds--but did a pretty amazing job of segmentating the image. Note how
% well it handled overlapping cells (circles), for instance:
togglefig Blowup
imshow(img)
xlims = [406 520];
ylims = [52 143];
set(gca,'xlim',xlims,'ylim',ylims)
inImageCircles = find(inpolygon(circen(:,1), circen(:,2), xlims([1 2 2 1]), ylims([1 1 2 2])));
for ii = 1 : numel(inImageCircles)
    rectangle('Position',...
        [circen(inImageCircles(ii),1) - cirrad(inImageCircles(ii)),...
        circen(inImageCircles(ii),2) - cirrad(inImageCircles(ii)),...
        2*cirrad(inImageCircles(ii)),...
        2*cirrad(inImageCircles(ii))],...
        'Curvature', [1,1], 'edgecolor', 'b', 'linewidth', 1.5);
end
%%
% If you do any image processing, you might recognize how Tao's function
% made a very challenging problem pretty manageable. If you're not an image
% processing expert, this might seem a bit arcane to you...but hopefully
% you'll find some value in it anyway. I'd love to hear your comments!

%%
% _Brett Shoelson_
% _Copyright 2008 The MathWorks, Inc._

Draw triangle and apply Morphology operations on it

 rows = 240;columns = 320;
grayImage = zeros(rows, columns, 'uint8');
xCoords = [100 200 300];
yCoords = [80 160 80];
mask = poly2mask(xCoords, yCoords, rows, columns);
grayImage(mask) = 150; % or whatever value you want.
imshow(grayImage);

>>  B=im2bw(grayImage);
>> figure,imshow(B);
>>  C=imfill(B,'holes');
>> figure,imshow(C);
>>  [Label,Total]=bwlabel(C,8);
>>  figure,imshow(C); 

Thursday, 3 July 2014

how to detect nose in matlab


vid = imaq.VideoDevice('winvideo', 1, 'YUY2_640x480','ROI',[1 1 640 480]);
videoFrame = step(vid);
bbox            = step(faceDetector, videoFrame);
noseDetector = vision.CascadeObjectDetector('Nose');
faceImage    = imcrop(videoFrame,bbox(1,:));
noseBBox     = step(noseDetector,faceImage);
noseBBox(1,1:2) = noseBBox(1,1:2) + bbox(1,1:2);
tracker = vision.HistogramBasedTracker;
initializeObject(tracker, hueChannel, noseBBox(1,:));

% Create a video player object for displaying video frames.
ROI = get(vid,'ROI');
videoSize = [ROI(3) ROI(4)];
videoPlayer  = vision.VideoPlayer('Position',[300 300 videoSize(1:2)+30]);

To detect the upper body part of an image

bodyDetector = vision.CascadeObjectDetector('UpperBody');
bodyDetector.MinSize = [25 25];
%bodyDetector.MaxSize=[90 90];
bodyDetector.ScaleFactor=1.02;
I2 = imread('untitled.jpg');
bboxBody = step(bodyDetector, I2);
disp(bboxBody);
IBody = insertObjectAnnotation(I2, 'rectangle',bboxBody,'Upper Body');
figure(1);
imshow(IBody);
title('Detected upper bodies');



 bodyDetector = vision.CascadeObjectDetector('UpperBody');
 bodyDetector.MinSize = [60 60];
 bodyDetector.MergeThreshold = 10;
 I2 = imread('untitled.jpg');
 bboxBody = step(bodyDetector, I2);
 IBody = insertObjectAnnotation(I2, 'rectangle',bboxBody,'Upper Body');
 figure, imshow(IBody), title('Detected upper bodies');




Wednesday, 2 July 2014

detect face and mouth using viola jones technique in computer vision tool box

a=imread('img.jpg');
MouthDetect = vision.CascadeObjectDetector('Mouth','MergeThreshold',16);
BB=step(MouthDetect,a);
figure,
imshow(I); hold on
for i = 1:size(BB,1)
rectangle('Position',BB(i,:),'LineWidth',4,'LineStyle','-','EdgeColor','r');
end
title('Mouth Detection');
hold off;

Detect Surf Features

This deals with matching surf features on an image. It has a function called  detectMSERFFeatues which finds out interest points in an image and mark them with a circles.


I = imread('cameraman.tif');
regions = detectMSERFeatures(I);
figure; imshow(I); hold on;
plot(regions, 'showPixelList', true, 'showEllipses', false);
figure; imshow(I); hold on;
plot(regions); % by default, plot displays ellipses and centroids

how to draw a square template

 T=100;
f=zeros(128,128);
f(32:96,32:96)=255;
[g1, t1]=edge(f, 'sobel', 'vertical');
imshow(g1);
t1

t1 =

   31.9372

>> sigma=1;
f=zeros(128,128);
f(32:96,32:96)=255;
[g3, t3]=edge(f, 'canny', [0.04 0.10], sigma);
figure,imshow(g3);
t3

t3 =

    0.0400    0.1000

Tuesday, 1 July 2014

how to draw a square on an object in matlab

For example type the following command in Matlab which supports Computer Vision toolbox

>> ex_vision_track_object

It opens a simulink and the design is visible and click on run in the window.
It displays a square even though the object is displaced 

detection of vehicle in motion

>> % Object for reading video file.
filename = 'viptraffic.avi';
hVidReader = vision.VideoFileReader(filename, 'ImageColorSpace', 'RGB',...
                              'VideoOutputDataType', 'single');
>> hOpticalFlow = vision.OpticalFlow( ...
    'OutputValue', 'Horizontal and vertical components in complex form', ...
    'ReferenceFrameDelay', 3);
>> hMean1 = vision.Mean;
hMean2 = vision.Mean('RunningMean', true);
>> hMedianFilt = vision.MedianFilter;
>> hclose = vision.MorphologicalClose('Neighborhood', strel('line',5,45));
>> hblob = vision.BlobAnalysis(...
    'CentroidOutputPort', false, 'AreaOutputPort', true, ...
    'BoundingBoxOutputPort', true, 'OutputDataType', 'double', ...
    'MinimumBlobArea', 250, 'MaximumBlobArea', 3600, 'MaximumCount', 80);
>> herode = vision.MorphologicalErode('Neighborhood', strel('square',2));
>> hshapeins1 = vision.ShapeInserter('BorderColor', 'Custom', ...
                                  'CustomBorderColor', [0 1 0]);
hshapeins2 = vision.ShapeInserter( 'Shape','Lines', ...
                                   'BorderColor', 'Custom', ...
                                   'CustomBorderColor', [255 255 0]);
>> htextins = vision.TextInserter('Text', '%4d', 'Location',  [1 1], ...
                               'Color', [1 1 1], 'FontSize', 12);
>> sz = get(0,'ScreenSize');
pos = [20 sz(4)-300 200 200];
hVideo1 = vision.VideoPlayer('Name','Original Video','Position',pos);
pos(1) = pos(1)+220; % move the next viewer to the right
hVideo2 = vision.VideoPlayer('Name','Motion Vector','Position',pos);
pos(1) = pos(1)+220;
hVideo3 = vision.VideoPlayer('Name','Thresholded Video','Position',pos);
pos(1) = pos(1)+220;
hVideo4 = vision.VideoPlayer('Name','Results','Position',pos);

% Initialize variables used in plotting motion vectors.
lineRow   =  22;
firstTime = true;
motionVecGain  = 20;
borderOffset   = 5;
decimFactorRow = 5;
decimFactorCol = 5;
>> while ~isDone(hVidReader)  % Stop when end of file is reached
    frame  = step(hVidReader);  % Read input video frame
    grayFrame = rgb2gray(frame);
    ofVectors = step(hOpticalFlow, grayFrame);   % Estimate optical flow

    % The optical flow vectors are stored as complex numbers. Compute their
    % magnitude squared which will later be used for thresholding.
    y1 = ofVectors .* conj(ofVectors);
    % Compute the velocity threshold from the matrix of complex velocities.
    vel_th = 0.5 * step(hMean2, step(hMean1, y1));

    % Threshold the image and then filter it to remove speckle noise.
    segmentedObjects = step(hMedianFilt, y1 >= vel_th);

    % Thin-out the parts of the road and fill holes in the blobs.
    segmentedObjects = step(hclose, step(herode, segmentedObjects));

    % Estimate the area and bounding box of the blobs.
    [area, bbox] = step(hblob, segmentedObjects);
    % Select boxes inside ROI (below white line).
    Idx = bbox(:,1) > lineRow;

    % Based on blob sizes, filter out objects which can not be cars.
    % When the ratio between the area of the blob and the area of the
    % bounding box is above 0.4 (40%), classify it as a car.
    ratio = zeros(length(Idx), 1);
    ratio(Idx) = single(area(Idx,1))./single(bbox(Idx,3).*bbox(Idx,4));
    ratiob = ratio > 0.4;
    count = int32(sum(ratiob));    % Number of cars
    bbox(~ratiob, :) = int32(-1);

    % Draw bounding boxes around the tracked cars.
    y2 = step(hshapeins1, frame, bbox);

    % Display the number of cars tracked and a white line showing the ROI.
    y2(22:23,:,:)   = 1;   % The white line.
    y2(1:15,1:30,:) = 0;   % Background for displaying count
    result = step(htextins, y2, count);

    % Generate coordinates for plotting motion vectors.
    if firstTime
      [R C] = size(ofVectors);            % Height and width in pixels
      RV = borderOffset:decimFactorRow:(R-borderOffset);
      CV = borderOffset:decimFactorCol:(C-borderOffset);
      [Y X] = meshgrid(CV,RV);
      firstTime = false;
    end

    % Calculate and draw the motion vectors.
    tmp = ofVectors(RV,CV) .* motionVecGain;
    lines = [Y(:), X(:), Y(:) + real(tmp(:)), X(:) + imag(tmp(:))];
    motionVectors = step(hshapeins2, frame, lines);

    % Display the results
    step(hVideo1, frame);            % Original video
    step(hVideo2, motionVectors);    % Video with motion vectors
    step(hVideo3, segmentedObjects); % Thresholded video
    step(hVideo4, result);           % Video with bounding boxes
end

release(hVidReader);
>> 

Thursday, 19 June 2014

Circular hough Transfrom matlab code


%E-Edge image which is binary image
%distMax=diagonal
[iHeight,iWidth]=size(E);
%max possible distance from origin
distMax=round(sqrt(iHeight^2+iWidth^2);
%range of theta values
theta=-90:1:89
rho=-distMax:1:distMax;
%alocate accumulator array
H=zeros(length(rho),length(theta));

for ix=1:iWidth
   for iy=1:iHeight
      if E(iy,ix)==0

      % fill accumulator
       for iTheta=1:length(theta)
           t=theta(iTheta)*pi/180;  %get angle in radius

            %calculate distance from origin, given angle
             dist=ix*cost(t)+iy*sint(t);

             % find rho value closest to this
             [d,iRho]=min(abs(rho-dist));
             if d<=1
               %inc accumulator array
               H(iRho,iTheta)=H(iRho,ITheta)+1;
             end
           end
        end
     end
 end

Wednesday, 18 June 2014

Morphology in matlab

Morphology

strel constructs structuring elements with a variety of shapes and sizes. Its basic syntax is
se=strel(shape,parameters)

se1 = strel('square',11)      % 11-by-11 square
se2 = strel('line',10,45)     % length 10, angle 45 degrees
se3 = strel('disk',15)        % disk, radius 15
se4 = strel('ball',15,5)      % ball, radius 15, height 5



strel(’diamond’,R)
Creates a flat, diamond-shaped structuring element,where R specifies the distance from the structuring element origin to the extreme points of the diamond
strel(’disk’,R)
Creates a flat, disk-shaped structuring element with radius R.
strel(’line’,LEN,DEG)
Creates a flat, linear structuring element, where LEN specifies the length, and DEG specifies the angle (in degrees) of the line, as measured in a counterclock-wise direction from the horizontal axes
strel(’octagon’,R)
Creates a flat, octagonal structuring element, where R specifies the distance from the structuring element origin to the sides of the octagon, as measured along the horizontal and vertical axes. R must be a nonnegative multiple of 3
strel(’pair’,OFFSET)
Creates a flat structuring element containing two members. One member is located at the origin. The second member’s location is specified by the vector OFFSET, which must be a two-element vector of integers.
strel(’periodicline’,P,V)
Creates a flat structuring element containing 2*P+1members.Vis a two-element vector con-taining integer-valued row and column offsets.One structuring element member is located atthe origin. The other members are located at1*V,-1*V,2*V,-2*V,V.
strel(’rectangle’,MN)
Creates a flat, rectangle-shaped structuring element, where MN specifies the size. MN must be a two- element vector of nonnegative integers. The first ele- ment of MN is the number of rows in the structuring el-ement; the second element is the number of columns
strel(’square’,W)
Creates a square structuring element whose width is W pixels. W must be a nonnegative integer scalar
strel(NHOOD)
Creates a structuring element of arbitrary shape. NHOOD is a matrix of 0s and 1s that specifies the shape

a=imread(‘image.jpg’);
% invert the array
a=255-a;
%create structuring element
se=strel(‘disk’,7);
a_erode=imerode(a,se);
a_dilate=imdilate(a,se);
a_open=imopen(a,se);
a_closed=imclose(a,se);


or

a=imread(‘image.jpg’);
B=[0 1 0;1 1 1;0 1 0];
A2=imdilate(a,B);

convert frames to video

ImagesFolder=uigetdir;
jpegFiles = dir(strcat(ImagesFolder,'\*.jpg'));
S = [jpegFiles(:).datenum];
[S,S] = sort(S);
jpegFilesS = jpegFiles(S);
% create a video file object called MyVideo
VideoFile=strcat(ImagesFolder,'\MyVideo');
writerObj = VideoWriter(VideoFile);
%Define the video frames per second
fps= 10;
writerObj.FrameRate = fps;
%Open file for writing video data
open(writerObj);
%convert them to movie frames using im2frame and writing the video data to file using writeVideo
for t= 1:length(jpegFilesS)
    Frame=imread(strcat(ImagesFolder,'\',jpegFilesS(t).name));
    writeVideo(writerObj,im2frame(Frame));
end
close(writerObj);

Monday, 16 June 2014

Circular Hough Transform


                   First we find all the edge in the image .This step has nothing to do with Hough transform and any edge detection technique can be used .It could be canny or sobel or prewitt. Here we used sobel edge detection technique. At each edge point we draw a circle with centre in the point with the desired radius .This circle is drawn in the parameter space, such that our x!axis is the a! value and y!axis in the b!value and z! axis is the radii. At the coordinates which belongs to the parameter of the drawn circle .We increment the value in our accumulator matrix which essentially has same size as parameter space .In this way we sweep over energy edge point in the input image drawing circle with the desired circle with desired radii and incrementing the value in our accumulator

When every edge point and every desired radius is used ,we can turn our attention to accumulator will now contain numbers corresponding to the number of circles passing through the individual coordinate .

The parameter space for CHT







One important difference between the Hough Transform and other approaches is resistance of the former to noise in the image and its tolerance towards holes in the boundary line.

Robert cross operator

The Robert cross operator performs a simple, quick to compute, 2-D spatial gradient measurement on image. The output pixels values at each point represent the absolute magnitude of the spatial gradient of the input at that point.

The operator consists of a pair of 2×2 convolution masks  kernels as shown. One kernel is simply rotated by the other by 90 degree. It is very similiar to the Sobel operator

Gx=
Gy
These masks are designed to respond maximally to edges running at 45° o the pixel grid
Then these are applied to the input image to produce separate measurements of gradient component in each orientation. Gx and Gy
The gradient magnitude is given by
The angle of orientation of the edge giving rise to the spatial gradient

Saturday, 14 June 2014

Convert Video to frames in matlab

The videoReader takes the input video. It creates a folder called snaps. If the directory is not there, it creates using mkdir
The frames are read now and stored in Frame. Later the file is taken and written into the output folder. The frame is then incremented.


clc;
close all;
clear all;
filename = 'rhinos.avi';
mov = VideoReader(filename);
opFolder = fullfile(cd, 'snaps');
if ~exist(opFolder, 'dir')
      mkdir(opFolder);
end
numFrames = mov.NumberOfFrames;
numFramesWritten = 0;
for t = 1 : numFrames
    Frame = read(mov, t);
    opBaseFileName = sprintf('%3.3d.png', t);
     opFullFileName = fullfile(opFolder, opBaseFileName);
     imwrite(Frame, opFullFileName, 'png');
     Indicate = sprintf('Wrote frame %4d of %d.', t, numFrames);
     disp(Indicate);
     numFramesWritten = numFramesWritten + 1;
end
Indicate = sprintf('Wrote %d frames to folder "%s"',numFramesWritten, opFolder);
disp(Indicate);

Extract frames from video



The following code takes input as a video reader and read the number of frames and writes to a directory.
and the output is a video of the frames which are sorted in certain time intervals.

workingDir = tempname;
mkdir(workingDir);
mkdir(workingDir,'images');
shuttleVideo = VideoReader('shuttle.avi');
for ii = 1:shuttleVideo.NumberOfFrames
    img = read(shuttleVideo,ii);
    imwrite(img,fullfile(workingDir,'images',sprintf('img%d.jpg',ii)));
end
imageNames = dir(fullfile(workingDir,'images','*.jpg'));
imageNames = {imageNames.name}';
disp(imageNames(1:10));
imageStrings = regexp([imageNames{:}],'(\d*)','match');
imageNumbers = str2double(imageStrings);
[~,sortedIndices] = sort(imageNumbers);
sortedImageNames = imageNames(sortedIndices);
disp(sortedImageNames(1:10));
outputVideo = VideoWriter(fullfile(workingDir,'shuttle_out.avi'));
outputVideo.FrameRate = shuttleVideo.FrameRate;
open(outputVideo);
for ii = 1:length(sortedImageNames)
    img = imread(fullfile(workingDir,'images',sortedImageNames{ii}));
    writeVideo(outputVideo,img);
end
close(outputVideo);
shuttleAvi = VideoReader(fullfile(workingDir,'shuttle_out.avi'));
mov(shuttleAvi.NumberOfFrames) = struct('cdata',[],'colormap',[]);
for ii = 1:shuttleAvi.NumberOfFrames
    mov(ii) = im2frame(read(shuttleAvi,ii));
end
set(gcf,'position', [150 150 shuttleAvi.Width shuttleAvi.Height])
set(gca,'units','pixels');
set(gca,'position',[0 0 shuttleAvi.Width shuttleAvi.Height])
image(mov(1).cdata,'Parent',gca);
axis off;
movie(mov,1,shuttleAvi.FrameRate);
displayEndOfDemoMessage(mfilename)







How to acquire video from matlab in real time and convert to frames

To get the information about devices

info=imaqhwinfo
info.InstalledAdaptors
info = imaqhwinfo('winvideo')
dev_info = imaqhwinfo('winvideo', 1)
info.DeviceInfo
info.DeviceInfo.SupportedFormats
%celldisp(dev_info.SupportedFormats);
imaqtool
How to acquire video from matlab in real time

vid=videoinput('winvideo',1);
preview(vid);
start(vid);
% foto=getsnapshot(vid);
%image(foto);
im=getdata(vid,1);figure,imshow(im);
imwrite(im,'testimage.jpg');


  • imaqhwinfo gives information about the existing adaptors for your webcam device
  • winvideo is one of the adaptors.
  • Further information pertaining to the device can be obtained by imaqhwinfo('winvideo',1) where 1 is the Device ID you saw earlier
  • The resolution (800×600, 1024×768, 1600×1200, etc.), format (RGB, YUV, etc.) which needs to be selected when creating a video object.
  • create a videoinput object
    ->vidobj = videoinput('winvideo',1,'RGB_1024x768');
  • to start your video object start(vidobj)
  • You can obtain snapshots of capture by using the frame = getsnapshot(vidobj)
  • view the continuous stream of frames by saying preview(vidobj);
  • A stop(vidobj) followed by delete(vidobj) is the best way to follow.
  • All the options can be seen by imaqhelp(videoinput).