Wednesday 30 January 2013

Client server program Matlab Code


server.m


import java.net.*;
import java.io.*;

%% Create Socket
port = 20;
    %input('Enter port number: ');
Server = ServerSocket (port);
disp('Waiting for a connection...')
connected = Server.accept;

iStream = connected.getInputStream;
oStream = connected.getOutputStream;

% Greets the client
oStream.sendS('Welcome client!')

% Waiting for messages from client
while ~(iStream.available)
end
readS(iStream);

%% Communication
msg = '';
while isempty(strfind(msg,'!q'))
% Waits for messages from client
while ~(iStream.available)
end
msg = readS(iStream);

if isempty(strfind(msg,'!q'))
 % Sends message to client
 disp 'Server''s turn!'
 %cmd = input('Toclient>> ', 's');
      cmd = 'hey im feeling okey!'
 oStream.sendS(cmd);

else
 oStream.sendS('!q');
end
end

pause(1)
connected.close;
disp (['Connection ended: ' datestr(now)]);

client.m


import java.net.*;
import java.io.*;

%% Create Socket and Connect to server
% Note that I am connecting to localhost, but you may change that to the corresponding machine IP that is running the server.
port = 20;
    %input('Enter port number: ');
disp('Connecting to server...')
clientSocket = Socket('localhost', port);

iStream = clientSocket.getInputStream;
oStream = clientSocket.getOutputStream;

% Greets the server on connection is accepted
oStream.sendS('Hi Server!')

% Waiting for messages from Server
while ~(iStream.available)
end
readS(iStream);
msg = '';
while isempty(strfind(msg,'!q'))
% Sends message to server
disp 'Client''s turn!'
cmd = input('ToServer>> ', 's');
oStream.sendS(cmd);

% Waits for replies from server
while ~(iStream.available)
end
msg = readS(iStream);
end
clientSocket.close
disp (['Connection ended: ' datestr(now)]);

readS.m


function b = readS(iStream)

disp 'Reply:'

% Number of messages
n = iStream.available;

% Buffer size = 500 characters
b = zeros(1,500);
for i = 1:n
   b(i) = iStream.read();
end

if (b(1) ~= 0)
   disp (char(b))
end
disp ('')

sendS.m


    function sendS(oStream,str)
oStream.write(int8([str 10]))





Sunday 27 January 2013

Access serial port using Matlab code


AccessSerialPort.m


clear all;
close all;

s = serial('COM1');  %assigns the object s to serial port

set(s, 'InputBufferSize', 256);  %number of bytes in inout buffer
set(s, 'FlowControl', 'hardware');
set(s, 'BaudRate', 9600);
set(s, 'Parity', 'none');
set(s, 'DataBits', 8);
set(s, 'StopBit', 1);
set(s, 'Timeout',10);
disp(get(s,'Name'));
prop(1)=(get(s,'BaudRate'));
prop(2)=(get(s,'DataBits'));
prop(3)=(get(s, 'StopBit'));
prop(4)=(get(s, 'InputBufferSize'));

disp(['Port Setup Done!!',num2str(prop)]);

fopen(s);           %opens the serial port
t=1;
disp('Running');
x=0;
while(t<200 p="">   a =fread(s);
   a=max(a);
   x =[x a];
   plot(x);
   axis auto;
   grid on;
   disp([num2str(t),'th iteration max= ',num2str(a)]);
   hold on;
   t=t+1;
   a=0;
   drawnow;
end

fclose(s); %close the serial port

Saturday 26 January 2013

Face Detection Matlab Code


face_detect.m


function []=detect_face(I)

close all;
Faces=[];
numFaceFound=0;

I=double(I);

H=size(I,1);
W=size(I,2);
R=I(:,:,1);
G=I(:,:,2);
B=I(:,:,3);
YCbCr=rgb2ycbcr(I);
Y=YCbCr(:,:,1);
minY=min(min(Y));
maxY=max(max(Y));
Y=255.0*(Y-minY)./(maxY-minY);
YEye=Y;
Yavg=sum(sum(Y))/(W*H);

T=1;
if (Yavg<64)
    T=1.4;
elseif (Yavg>192)
    T=0.6;
end

if (T~=1)
    RI=R.^T;
    GI=G.^T;
else
    RI=R;
    GI=G;
end

C=zeros(H,W,3);
C(:,:,1)=RI;
C(:,:,2)=GI;
C(:,:,3)=B;

figure,imshow(C/255);
title('Lighting compensation');
YCbCr=rgb2ycbcr(C);
Cr=YCbCr(:,:,3);

S=zeros(H,W);
[SkinIndexRow,SkinIndexCol] =find(10<Cr & Cr<45);
for i=1:length(SkinIndexRow)
    S(SkinIndexRow(i),SkinIndexCol(i))=1;
end

figure,imshow(S);
title('skin');
SN=zeros(H,W);
for i=1:H-5
    for j=1:W-5
        localSum=sum(sum(S(i:i+4, j:j+4)));
        SN(i:i+5, j:j+5)=(localSum>12);
    end
end

figure,imshow(SN);
title('skin with noise removal');
L = bwlabel(SN,8);
BB  = regionprops(L, 'BoundingBox');
bboxes= cat(1, BB.BoundingBox);
widths=bboxes(:,3);
heights=bboxes(:,4);
hByW=heights./widths;

lenRegions=size(bboxes,1);
foundFaces=zeros(1,lenRegions);

rgb=label2rgb(L);
figure,imshow(rgb);
title('face candidates');
for i=1:lenRegions
 
    if (hByW(i)>1.75 || hByW(i)<0.75)
        continue;
    end
    if (heights(i)<20 && widths(i)<20)
        continue;
    end
    CurBB=bboxes(i,:);
    XStart=CurBB(1);
    YStart=CurBB(2);
    WCur=CurBB(3);
    HCur=CurBB(4);
    rangeY=int32(YStart):int32(YStart+HCur-1);
    rangeX= int32(XStart):int32(XStart+WCur-1);
    RIC=RI(rangeY, rangeX);
    GIC=GI(rangeY, rangeX);
    BC=B(rangeY, rangeX);
 
    figure, imshow(RIC/255);
    title('Possible face R channel');
    M=zeros(HCur, WCur);
    theta=acos( 0.5.*(2.*RIC-GIC-BC) ./ sqrt( (RIC-GIC).*(RIC-GIC) + (RIC-BC).*(GIC-BC) ) );
    theta(isnan(theta))=0;
    thetaMean=mean2(theta);
    [MouthIndexRow,MouthIndexCol] =find(theta<thetaMean/4);
    for j=1:length(MouthIndexRow)
        M(MouthIndexRow(j),MouthIndexCol(j))=1;
    end
    Hist=zeros(1, HCur);
 
    for j=1:HCur
        Hist(j)=length(find(M(j,:)==1));
    end
 
    wMax=find(Hist==max(Hist));
    wMax=wMax(1);
 
    if (wMax < WCur/6)
        continue;
    end
 
    figure, imshow(M);
    title('Mouth map');
    eyeH=HCur-wMax;
    eyeW=WCur;
 
    YC=YEye(YStart:YStart+eyeH-1, XStart:XStart+eyeW-1);
 
    E=zeros(eyeH,eyeW);
    [EyeIndexRow,EyeIndexCol] =find(65<YC & YC<80);
    for j=1:length(EyeIndexRow)
        E(EyeIndexRow(j),EyeIndexCol(j))=1;
    end
    EyeExist=find(Hist>0.3*wMax);
    if (~(length(EyeExist)>0))
        continue;
    end
 
    foundFaces(i)=1;
    numFaceFound=numFaceFound+1;
 
end
disp('Number of faces found');
numFaceFound;

if (numFaceFound>0)
    disp('Indices of faces found: ');
    ind=find(foundFaces==1);
    CurBB=bboxes(ind,:);
    CurBB
else
    close all;
end

end

run the file using

main.m


I=double(imread('sample.jpg'));
detect_face(I);

You might also like : Skin Detection



Controlling Keyboard switches with Matlab code


import java.awt.Robot;
import java.awt.event.*;

robot = Robot();

robot.keyPress(KeyEvent.VK_CAPS_LOCK);
robot.keyRelease(KeyEvent.VK_CAPS_LOCK);

I have shown with an example of "CAPS LOCK",but it can be replaced with the other buttons also


Friday 25 January 2013

Skin Detection Matlab Code

skin_detect.m

function [out bin] = generate_skinmap(filename)

 
    if nargin > 1 | nargin < 1
        error('usage: generate_skinmap(filename)');
    end;
    img_orig = imread(filename);
    height = size(img_orig,1);
    width = size(img_orig,2);
    out = img_orig;
    bin = zeros(height,width);
    img = grayworld(img_orig);  
    img_ycbcr = rgb2ycbcr(img);
    Cb = img_ycbcr(:,:,2);
    Cr = img_ycbcr(:,:,3);
    [r,c,v] = find(Cb>=77 & Cb<=127 & Cr>=133 & Cr<=173);
    numind = size(r,1);
    for i=1:numind
        out(r(i),c(i),:) = [0 0 255];
        bin(r(i),c(i)) = 1;
    end
    imshow(img_orig);
    figure; imshow(out);
    figure; imshow(bin);
end

run.m


clc;
skin_detect('sample.jpg');


You might also like : Face Detection



RSA algorithm implementation using Matlab code

crypt.m

function mc = crypt(M,N,e)
e=dec2bin(e);
k = 65535;
c  = M;
cf = 1;
cf=mod(c*cf,N);
for i=k-1:-1:1
    c = mod(c*c,N);
    j=k-i+1;
     if e(j)==1
         cf=mod(c*cf,N);
     end
end
mc=cf;

dec2bin.m

function a = dec2bin(d)
i=1;
a=zeros(1,65535);
while d >= 2
    r=rem(d,2);
    if r==1
        a(i)=1;
    else
        a(i)=0;
    end
    i=i+1;
    d=floor(d/2);
end
if d == 2
    a(i) = 0;
else
    a(i) = 1;
end
x=[a(16) a(15) a(14) a(13) a(12) a(11) a(10) a(9) a(8) a(7) a(6) a(5) 

initialize.m


function [Pk,Phi,d,e] = intialize(p,q)
clc;
disp('Intaializing:');
Pk=p*q;
Phi=(p-1)*(q-1);
%Calculate the value of e
x=2;e=1;
while x > 1
    e=e+1;
    x=gcd(Phi,e);
end
%Calculate the value of d
i=1;
r=1;
while r > 0
    k=(Phi*i)+1;
    r=rem(k,e);
    i=i+1;
end
d=k/e;
clc;
disp(['The value of (N) is: ' num2str(Pk)]);
disp(['The public key (e) is: ' num2str(e)]);
disp(['The value of (Phi) is: ' num2str(Phi)]);
disp(['The private key (d)is: ' num2str(d)]);

rsa.m

clc;
disp('Implementation of RSA Algorithm');
clear all; close all;
p = input('\nEnter the value of p: ');
q = input('\nEnter the value of q: ');
[Pk,Phi,d,e] = intialize(p,q);
M = input('\nEnter the message: ','s');
x=length(M);
c=0;
for j= 1:x
    for i=0:122
        if strcmp(M(j),char(i))
            c(j)=i;
        end
    end
end
disp('ASCII Code of the entered Message:');
disp(c); 
% % %Encryption
for j= 1:x
   cipher(j)= crypt(c(j),Pk,e); 
end
disp('Cipher Text of the entered Message:');
disp(cipher);
% % %Decryption
for j= 1:x
   message(j)= crypt(cipher(j),Pk,d); 
end
disp('Decrypted ASCII of Message:');
disp(message);
disp(['Decrypted Message is: ' message]);




Motion Detection using Camshift algorithm Matlab code


There are two files included.

1.convert video frames using this .m file


clc;
cd frames;

for i = 2:107,
    filename1 = sprintf('%3.3i.png', i);
    filename2 = sprintf('%3.3i.png', i-1);
    A = imread(filename1, 'png');
    A = RGB2GRAY(A);
 
    B = imread(filename2, 'png');
    B = RGB2GRAY(B);
 
    C = imabsdiff(A,B);
    C = medfilt2(C, [5 5]);
    imwrite(C, sprintf('Frame %4.4d.png', i), 'png');
end

cd ..

disp('Done.');


2. Camshift.m



clc;
disp('Running...');
close all;
clear;
cd frames;

    WHITE = 255;

    % Threshold of convergence (in pixels for each deg. of freedom)
T = 1;
 
    % Number of pixels to expand search window by.
    P = 5;

avi = avifile('output1.avi');

% Initial search window size.
%W = [10 10];
W = [99 99];

% Initial location of search window.
%L = [95 193];
L = [71 141];

% For plotting motion
Xpoints=[];
Ypoints=[];

disp('Frame: Coordinates');

for frame = 1:44,
filename = sprintf('%3.3i.png', frame);
R = imread(filename, 'png');

% Convert image from RGB space to HSV space
I = rgb2hsv(R);

% Extract the hue information
I = I(:,:,1);
    I = roicolor(I, 0.83, 1.0);
 
    % Initialization
    oldCamL = [0 0];
    MeanConverging = 1;

    for i = L(1) : L(1)+W(1),
        x = i;
        y = L(2);
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y,:) = 0;
        end
    end
 
    for i = L(1) : L(1)+W(1),
        x = i;
        y = L(2) + W(2);
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y, :) = 0;
        end
    end  
 
    for i = L(2) : L(2)+W(2),
        x = L(1);
        y = i;
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y, :) = 0;
        end
    end  

    for i = L(2) : L(2)+W(2),
        x = L(1)+W(1);
        y = i;
        if x > size(I,1) | y > size(I,2) | x < 1 | y < 1
            continue;
        else
            R(x, y, :) = 0;
        end
    end  

M00 = 0.0;
for i = L(1)-P : (L(1)+W(1)+P),
            for j = L(2)-P : (L(2)+W(2)+P),
                if i > size(I,1) | j > size(I,2) | i < 1 | j < 1
                    continue;
                end
                M00 = M00 + double(I(i,j));
            end
end

M10 = 0.0;
for i = L(1)-P : (L(1)+W(1)+P),
            for j = L(2)-P : (L(2)+W(2)+P),
                if i > size(I,1) | j > size(I,2) | i < 1 | j < 1
                    continue;
                end
                M10 = M10 + i * double(I(i,j));
            end
end

M01 = 0.0;
for i = L(1)-P : (L(1)+W(1)+P),
            for j = L(2)-P : (L(2)+W(2)+P),
                if i > size(I,1) | j > size(I,2)| i < 1 | j < 1
                    continue;
                end              
                M01 = M01 + j * double(I(i,j));
            end
end

xc = round(M10 / M00);
yc = round(M01 / M00);

oldL = L;
L = [floor(xc - (W(1)/2)) floor(yc - (W(2)/2))];
     
        % Check threshold
        if abs(oldL(1)-L(1)) < T | abs(oldL(2)-L(2)) < T
            MeanConverging = 0;
        end
    end
 
    s = round(1.1 * sqrt(M00));
    W = [ s      floor(1.2*s) ];
    L = [floor(xc - (W(1)/2)) floor(yc - (W(2)/2))];
 
    % Output the centroid's coordinates
    disp(sprintf('%3i:   %3i, %3i', frame, xc, yc));
    Xpoints = [Xpoints xc];
    Ypoints = [Ypoints yc];
 
    % Superimpose plus sign on to centroid of hand.
    plus_sign_mask = [0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     1 1 1 1 1 1 1 1 1 1 1 1 1;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0;
                     0 0 0 0 0 0 1 0 0 0 0 0 0];
sizeM = size(plus_sign_mask);
for i = -floor(sizeM(1) / 2):floor(sizeM(1) / 2),
        for j = -floor(sizeM(2) / 2):floor(sizeM(2) / 2),
            if plus_sign_mask(i+1+floor(sizeM(1) / 2), j+1+floor(sizeM(2) / 2)) == 1
                R(i+xc, j+yc, :) = WHITE;
            end
        end
end
% ----------------------------------------------------------------------
    % Display the probability image.
    I = rgb2hsv(R);
    S = [];
    S(:,:,1) = I(:,:,1);
    S(:,:,2) = I(:,:,1);  
    S(:,:,3) = I(:,:,1);
% Extract the hue information
    avi = addframe(avi, S);
 
end
disp('AVI move parameters:');
avi = close(avi)
plot(Ypoints,Xpoints, 'go' , Ypoints, Xpoints);
axis([0 320 0 240]);
cd ..
disp('Done.');








Thursday 24 January 2013

Motion Tracking using Kalman Filter Matlab Code



clear all; close all; clc

%% Read video into MATLAB using aviread
video = aviread('Roof1.AVI');
nframes = length(video);

% Calculate the background image by averaging the first 5 images
temp = zeros(size(video(1).cdata));
[M,N] = size(temp(:,:,1));
for i = 1:10
    temp = double(video(i).cdata) + temp;
end
imbkg = temp/10;

% Initialization for Kalman Filtering
centroidx = zeros(nframes,1);
centroidy = zeros(nframes,1);
predicted = zeros(nframes,4);
actual = zeros(nframes,4);

% % Initialize the Kalman filter parameters
% R - measurement noise,
% H - transform from measure to state
% Q - system noise,
% P - the status covarince matrix
% A - state transform matrix

R=[[0.2845,0.0045]',[0.0045,0.0455]'];
H=[[1,0]',[0,1]',[0,0]',[0,0]'];
Q=0.01*eye(4);
P = 100*eye(4);
dt=1;
A=[[1,0,0,0]',[0,1,0,0]',[dt,0,1,0]',[0,dt,0,1]'];

% loop over all image frames in the video
kfinit = 0;
th = 38;
for i=1:nframes
  imshow(video(i).cdata);
  hold on
  imcurrent = double(video(i).cdata);
 
  % Calculate the difference image to extract pixels with more than 40(threshold) change
  diffimg = zeros(M,N);
  diffimg = (abs(imcurrent(:,:,1)-imbkg(:,:,1))>th) ...
      | (abs(imcurrent(:,:,2)-imbkg(:,:,2))>th) ...
      | (abs(imcurrent(:,:,3)-imbkg(:,:,3))>th);

  % Label the image and mark
  labelimg = bwlabel(diffimg,4);
  markimg = regionprops(labelimg,['basic']);
  [MM,NN] = size(markimg);

  % Do bubble sort (large to small) on regions in case there are more than 1
  % The largest region is the object (1st one)
  for nn = 1:MM
      if markimg(nn).Area > markimg(1).Area
          tmp = markimg(1);
          markimg(1)= markimg(nn);
          markimg(nn)= tmp;
      end
  end

  % Get the upper-left corner, the measurement centroid and bounding window size
  bb = markimg(1).BoundingBox;
  xcorner = bb(1);
  ycorner = bb(2);
  xwidth = bb(3);
  ywidth = bb(4);
  cc = markimg(1).Centroid;
  centroidx(i)= cc(1);
  centroidy(i)= cc(2);

  % Plot the rectangle of background subtraction algorithm -- blue
  hold on
  rectangle('Position',[xcorner ycorner xwidth ywidth],'EdgeColor','b');
  hold on
  plot(centroidx(i),centroidy(i), 'bx');

  % Kalman window size
  kalmanx = centroidx(i)- xcorner;
  kalmany = centroidy(i)- ycorner;

  if kfinit == 0
      % Initialize the predicted centroid and volocity
      predicted =[centroidx(i),centroidy(i),0,0]' ;
  else
      % Use the former state to predict the new centroid and volocity
      predicted = A*actual(i-1,:)';
  end
  kfinit = 1;

  Ppre = A*P*A' + Q;
  K = Ppre*H'/(H*Ppre*H'+R);
  actual(i,:) = (predicted + K*([centroidx(i),centroidy(i)]' - H*predicted))';
  P = (eye(4)-K*H)*Ppre;

  % Plot the tracking rectangle after Kalman filtering -- red
  hold on
  rectangle('Position',[(actual(i,1)-kalmanx) (actual(i,2)-kalmany) xwidth ywidth],'EdgeColor','r','LineWidth',1.5);
  hold on
  plot(actual(i,1),actual(i,2), 'rx','LineWidth',1.5);
  drawnow;
end


Extracting frames from a Video file Matlab Code


%%%%%%              Extracting frames from a Video file Matlab Code           %%%%%%%


clc;
close all;

% Open an sample avi file

filename = '.\003.AVI';
mov = MMREADER(filename);

% 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);



You might also like : Frames to AVI using Matlab Code

Moving Mouse Pointer using Matlab code


clc;
import java.awt.Robot;
cursor = Robot;

cursor.mouseMove(0, 0);
screensize = get(0, 'screensize');
aspect_ratio = screensize(3)/screensize(4);
for i = 1:screensize(4)
cursor.mouseMove(aspect_ratio*i, i);
pause(0.005);
end

Controlling Mouse event using Matlab code


import java.awt.Robot;
import java.awt.event.*;

cursor = Robot;

cursor.mousePress(InputEvent.BUTTON3_MASK);
cursor.mouseRelease(InputEvent.BUTTON3_MASK);

%%%%%%%%%%%%%   Note %%%%%%%%%%%

BUTTON1 for left click
BUTTON2 for both
BUTTON3 for right click