Sunday 25 January 2015

Background Subtraction Tracking

Below code is implementation of the code in below link using opencv 3
https://bitbucket.org/ElissonMichael/tcc_implementacao/raw/595d58fe68e4b8ee49b211c904e28be1533c8efc/Background/NoBackgroundCam.py

Corresponding video at
https://www.youtube.com/watch?v=KRKKektCcok

import numpy as np
import cv2
maiorArea = 0
cap = cv2.VideoCapture(0)

if not(cap.isOpened()):
    cap.open()

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow("Webcam", frame)
    bkg=frame.copy()
    fundo = cv2.GaussianBlur(bkg,(3,3),0)
    print("OK")
    if cv2.waitKey(1) == 32:
        cv2.destroyWindow("Webcam")
        break
       
while True:
    ret, imagem = cap.read()
    mascara=imagem.copy()
    cinza=imagem.copy()
    #cv2.imshow("Webcam", imagem)
    imagem = cv2.GaussianBlur(imagem,(3,3),0)
    cv2.absdiff(imagem,fundo,mascara)
    gray = cv2.cvtColor(mascara, cv2.COLOR_BGR2GRAY)
    ret,thresh1 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    kernel = np.ones((3,3),np.uint8)
    dilated = cv2.dilate(thresh1,kernel,iterations = 18)
    cinza = cv2.erode(dilated,kernel,iterations = 10)
    _,contorno,heir=cv2.findContours(cinza,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    for cnt in contorno:
        vertices_do_retangulo = cv2.boundingRect(cnt)
        if (cv2.contourArea(cnt)> maiorArea):
            maiorArea = cv2.contourArea(cnt)
            retangulo_de_interesse = vertices_do_retangulo
           
        ponto1 = (retangulo_de_interesse[0], retangulo_de_interesse[1])
        ponto2 = (retangulo_de_interesse[0] + retangulo_de_interesse[2], retangulo_de_interesse[1] + retangulo_de_interesse[3])
        cv2.rectangle(imagem, ponto1, ponto2,(0,0,0), 2)
        cv2.rectangle(cinza, ponto1, ponto2, (255,255,255), 1)
        largura = ponto2[0] - ponto1[0]
        altura = ponto2[1] - ponto1[1]
        cv2.line(cinza,(ponto1[0]+largura/2,ponto1[1]),(ponto1[0]+largura/2,ponto2[1]),(255,255,255), 1)
        cv2.line(cinza,(ponto1[0],ponto1[1]+altura/2),(ponto2[0],ponto1[1]+altura/2), (255,255,255), 1)

    cv2.imshow("Mascara", mascara)
    cv2.imshow("Cinza", cinza)
   
    cv2.imshow("Webcam", imagem)
    cv2.imshow("Dilated", thresh1)
    #cv2.imshow("Fundo", dilated)
    if cv2.waitKey(1) & 0xFF == ord('q'):
            break
   

# Release everything if job is finished
cap.release()
cv2.destroyAllWindows()



OR

for cnt in contorno:
        vertices_do_retangulo = cv2.minAreaRect(cnt)
        if (cv2.contourArea(cnt)> maiorArea):
            maiorArea = cv2.contourArea(cnt)
            retangulo_de_interesse = cv2.boxPoints(vertices_do_retangulo)
            retangulo_de_interesse = np.int0(retangulo_de_interesse)
            cv2.drawContours(imagem,[retangulo_de_interesse],-1,(0,0,0), 2)
            cv2.drawContours(cinza,[retangulo_de_interesse],-1,(255,255,255), 1)

OR

import numpy as np
import cv2
maiorArea = 0
cap = cv2.VideoCapture(0)

if not(cap.isOpened()):
    cap.open()

while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow("Webcam", frame)
    bkg=frame.copy()
    fundo = cv2.blur(bkg,(5,5))
    print("OK")
    if cv2.waitKey(1) == 32:       
        break
       
while True:
    ret, imagem = cap.read()
    mascara=imagem.copy()
    cinza=imagem.copy()
    #cv2.imshow("Webcam", imagem)
    imagem = cv2.blur(imagem,(5,5))
    cv2.absdiff(imagem,fundo,mascara)
    gray = cv2.cvtColor(mascara, cv2.COLOR_BGR2GRAY)
    ret,thresh1 = cv2.threshold(gray,100,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    cinza = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, kernel)
    cinza = cv2.blur(cinza, (9,9))
    _,contorno,heir=cv2.findContours(cinza,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    for cnt in contorno:
        vertices_do_retangulo = cv2.boundingRect(cnt)
        if (cv2.contourArea(cnt)> maiorArea):
            maiorArea = cv2.contourArea(cnt)
            retangulo_de_interesse = vertices_do_retangulo
           
        ponto1 = (retangulo_de_interesse[0], retangulo_de_interesse[1])
        ponto2 = (retangulo_de_interesse[0] + retangulo_de_interesse[2], retangulo_de_interesse[1] + retangulo_de_interesse[3])
        cv2.rectangle(imagem, ponto1, ponto2,(0,0,0), 2)
        cv2.rectangle(cinza, ponto1, ponto2, (255,255,255), 1)
        largura = ponto2[0] - ponto1[0]
        altura = ponto2[1] - ponto1[1]
        cv2.line(cinza,(ponto1[0]+largura/2,ponto1[1]),(ponto1[0]+largura/2,ponto2[1]),(255,255,255), 1)
        cv2.line(cinza,(ponto1[0],ponto1[1]+altura/2),(ponto2[0],ponto1[1]+altura/2), (255,255,255), 1)

       
 
    cv2.imshow("Mascara", mascara)
    cv2.imshow("Cinza", cinza)
   
    cv2.imshow("Webcam", imagem)
    #cv2.imshow("Thresholded", thresh1)
    #cv2.imshow("Fundo", fundo)
    if cv2.waitKey(1) & 0xFF == ord('q'):
            break
   

# Release everything if job is finished
cap.release()
cv2.destroyAllWindows()




Tuesday 20 January 2015

neural network in matlab 2014

Each row in Training belongs to one training data.
Each row in GroupTrain has the class of the corresponding training data.

In neural network, the model is trained using training data.

%classification using TreeBagger
model1 = TreeBagger(100,Training,GroupTrain,    'nprint',10);
disp(model1);

%How good the model is classifying the training data can tested by the following command

[tumortypeTrainPred, tumortypeTrainPredScores] = predict(model1,Training);

%to check the prediction of the model with just one instance that is 25th training data.
[tumortypeTrainPred, tumortypeTrainPredScores] = predict(model1,Training(25,:));
========================================================
%some demos in matlab 2014
edit classify_wine_demo
edit cancerdetectdemonnet
edit appcr1


One can watch the below video if using matlab 2010b using nntool
https://www.youtube.com/watch?v=2Z4959acjKs

and
http://in.mathworks.com/products/neural-network/features.html#data-fitting%2C-clustering%2C-and-pattern-recognition

In MATLAB 2014, one can make use of the following APPS found under APPS tab
neural net clustering
neural net fitting
neural net pattern recognition 
========================================================
Some more examples
========================================================
ldaClass = classify(Training(:,1:2),Training(:,1:2),GroupTrain);
N=size(GroupTrain,1);
bad = ~strcmp(ldaClass,GroupTrain);
ldaResubErr = sum(bad) / N
[ldaResubCM,grpOrder] = confusionmat(GroupTrain,ldaClass)

========================================================
clear all;
close all;
load('net.mat');
% Create a Pattern Recognition Network
hiddenLayerSize = 200;
net = patternnet(hiddenLayerSize);


% Set up Division of Data for Training, Validation, Testing
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;


% Train the Network
[net,tr] = train(net,inputs,targets);

% Test the Network
outputs = net(inputs);
errors = gsubtract(targets,outputs);
performance = perform(net,targets,outputs)


% View the Network
view(net);
%save the network
save(net);
%To do prediction, you can use sim(net, inputs)

%To Test the network
testX = inputs(:,tr.testInd);
testT = targets(:,tr.testInd);

testY = net(testX);
testIndices = vec2ind(testY);
=======================================

Friday 16 January 2015

Principal Component Analysis Well Explained With an Example in MATLAB


1
3
5
4

Consider an image as shown above and the image is made as first column elements as shown below

X =    [1     2     4     3     5     9     4     2;
           5     4     7     4     3     2     1     3;
           3     2     4     5     6     2     1     2;
           4     1     3     2     2     1     3     4]

First column represents one feature vectorand has four dimensions and there are 8 feature vectors.
Here, dimensions < number of feature vectors.
[vecs,val]=eigs(X*X',2);% X*X' gives matrix of size 4x4 as 4x8*8x4 . Only first two largest eigen vectors are considered as eigs(X*X',2)
%So,  instead of storing 4 vectors, you store 2 vectors
wt1=vecs'*X(:,1);
reconstructed =vecs*wt1; % approximate of the original
wt2=vecs'*X(:,2);
reconstructed =vecs*wt2;

For example: if you have 4 feature vector and each feature has 8 dimensions as shown below

X =[     1     5     3     4;
            2     4     2     1;
            4     7     4     3;
            3     4     5     2;
            5     3     6     2;
            9     2     2     1;
            4     1     1     3;
            2     3     2     4];
[vecs,val]=eigs(X'*X,2);%This is done to simplify computation as X*X' gives matrix of size 8x8. This is the trick used by Pentland and Turk
ef=X*vecs;  % in order to get eigen vectors of X*X', we have to multiply X with eigen vectors of X'*X..
for i=1:size(ef,2)
ef(:,i)=ef(:,i)./norm(ef(:,i)); % u divide each shape by its norm
end
wt1=ef'*X(:,1); % Each shape of 8 dimensions is now represented in 4 dimensions as 2 eigen vectors considered
reconstructed =ef*wt1; % you  get first shape back
wt2=ef'*X(:,2);
reconstructed =vecs*wt2;


You  can get back the image

Friday 9 January 2015

Horizontal and vertical Flip using opencv and python

import numpy as np
import cv2

img=cv2.imread('1.png')
rimg=img.copy()
fimg=img.copy()
rimg=cv2.flip(img,1)
fimg=cv2.flip(img,0)
cv2.imshow("Original", img)
cv2.imshow("vertical flip", rimg)
cv2.imshow("horizontal flip", fimg)
cv2.waitKey(0)
cv2.destroyAllWindows()