顯示具有 MATLAB 標籤的文章。 顯示所有文章
顯示具有 MATLAB 標籤的文章。 顯示所有文章

2015年10月20日 星期二

[MATLAB] Gaussian Mixture Model (GMM) 高斯混合模型

高斯混合模型 Gaussian Mixture Model (GMM)


Gaussian Mixture Model (GMM) 高斯混合模型 常用於影像處理中背景消去(Background Subtraction)中建立影像背景模型。同時也可以應用在樣型識別(Pattern Recognition)以及機器學習(Machine Learning)領域中的分群方法(Clustering)。

常見的背景消去法


最簡單靜態的背景消去方法是事先拍一張背景影像B(X,Y,t),接下來再拍攝相同背景含有物體在內的影像I(X,Y,t),接著再將兩張影像相減,得到所有像素的差值,自行訂立一個閥值(Threshold),若大於閥值者,找出該相差值大於閥值像素與其所在位置,即可找到該物體(前景, Foreground )。

               |I(X,Y,t) - B(X,Y,t)| > Threshold

另一種應用於影片的背景消去方法是利用連續的影像,求出連續影像的平均值,以該平均值訂為背景,再利用上述的背景消方法找出物體。

但是上述的方式有以下優缺點

  • 優點 : 簡單、計算快速
  • 缺點 : 準確性不佳、影像幀數高則需要更多記憶體資源、若影像變動大則沒有一個固定的閥值(Ex. 白天到黑夜)

高斯混合模型 Gaussian Mixture Model (GMM) 


為了解決上述的問題,Stauffer, C. and Grimson, W.E.L 等人在其 Adaptive Background Mixture Models for Real-Time Tracking, Computer Vision and Pattern Recognition (1999) 的論文中提出一種具有適應性的方法來嘗試解決上述缺點。

若將一幀影像視作一個統計模型,例如,灰階影像直方圖即是針對像素灰階值,我們可以將某個灰階值出現的可能性視作一個機率事件,而如此,此即為機率模型。而所謂的機率模型,就是在針對不同幀的影像進行一個統計過程,並由未知數X來求得Y的相關資訊。但是所求得的結果不是一個準確的數值,而是代表例如該像素屬於前景物體像素的機率是多少(符合的機率有多高?),而非該像素是否屬於前景像素(Yes/No 的是非問題)。

而機率模型的好處就在於能夠判讀與操作的空間相對大了許多,而非非黑即白的問題。而在數學理論上,高斯模型能夠透過增加模型的個數以符合(fit)特定的機率分布情形。
(詳細的數學計算流程請參考這兩篇博文 聚类(1)——混合高斯模型 Gaussian Mixture Model 、 漫谈 Clustering (3): Gaussian Mixture Model)

若將自然分布(高斯分布)的概念引入這個問題中,我可以將像素視為同時有好幾個模式存在(Ex. 白天模式、傍晚模式、黑夜模式),及同時有好多個高斯模型(Gaussians)存在,此概念為mixture of adaptive Gaussians。若該像素不符合背景的高斯模型(Background Gaussian),則視作前景。我們可以將影像的分布機率視作K個高斯模型混合再一起(Mixture of Gaussians)

當然,GMM本身也是有優缺點


  • 優點 : 每個像素可以有不同的閥值、閥值可以隨不同帧的影像調整、物體可以成為背景的一部分而不破壞背景
  • 缺點 : 無法應對背景快速變動的光影變化、初始化的高斯模型(Gaussian)相當重要、太多參數需要決定
高斯混合模型的MATLAB實現方法

根據 MathWorks 官網的 vision.ForegroundDetector System object 項目中,得知

detector = vision.ForegroundDetector 這行指令所回傳的是經過 GMM偵測後所得到的前景物

體


下面是以MATLAB所撰寫的程式,使用的版本為R2014b,謝謝學弟黃博揚提供



%% - - Initail System - ->>
close all;
clear all;
clc;

%% - - Input Video - ->>
video_file = 'D:\20150922\2x2_B3\after_rot\1\canny20151018_4_otsu_canny_roi.avi';
video      = VideoReader(video_file);

% -- Video Parameter Setting -->
frameRate    = round(video.FrameRate);
nb_frame     = get(video, 'numberOfFrames');
duration     = video.Duration; 
resize_ratio = 1;
frame_offset = 0;

% -- Video Save Setting -->
video_save     = 0;                  %控制存檔與否
videoName      = '檔案名稱.avi';
videoExtension = 'Uncompressed AVI'; %檔案格式

% -- GMM Background Substraction Setting -->
trainFrame = fix(frameRate * duration);
initVariance = 10^2;
minRatio = 0.7;
numGauss = 8;
fgDetector = vision.ForegroundDetector('NumTrainingFrames',trainFrame,...
    'MinimumBackgroundRatio',minRatio,'NumGaussians',numGauss,...
    'InitialVariance',initVariance);
%% - - Read First Frame - ->>
frame = read(video,1 + frame_offset);
frame = imresize(frame,resize_ratio);
[h,w,~] = size(frame);

%% - - Initial Display - ->>
figure(1);
fig = imshow(frame,'border','tight');
hold on;

%% - - Run Tracking Program - ->>
for k = 1 : nb_frame - frame_offset
    tic;
    %% - - Read Frame & Pre-processing - ->>
    frame     = read(video,k + frame_offset);
    frame     = imresize(frame,resize_ratio);
    
    %  -- GMM Background Substraction -->
    segmentation = step(fgDetector,frame);  % foregroundMask = step(H,I), I = input image  
    
    %% - - Corner Detection Setting - ->>
    C = corner(frame(:,:,1), method, N);
    
    %% - - Display Image - ->>
    set(fig,'CData',segmentation);          % fig為圖形的握把物件代稱
    drawnow;
    
    %% - - Save Video - ->>
    if video_save == 1;
        FrameSave(k) = getframe(gcf);
    end
    toc;
end

%% - - Save Video - ->>
if video_save == 1
    VideoSave = VideoWriter(videoName,videoExtension);
    VideoSave.FrameRate = frameRate;
    open(VideoSave);
    writeVideo(VideoSave,FrameSave);
    close(VideoSave);
end



2015年5月22日 星期五

[MATLAB] GUI error problems

1. GUI Tutorial in Chinese

    Web site 1 and web site 2

2. GUI open file dialog - uigetfile

3. If you create a callback function in .m file and then delete it.

   It will pop out an error like this.

   Next time, don't delete  the code even if you don't need it.


2015年4月26日 星期日

[MATLAB] Hough Transform- line detection official tutorial

1. Official Tutorial
http://www.mathworks.com/help/images/hough-transform.html

2. CSDN
http://blog.csdn.net/xsjwangyb/article/details/10917945

2015年4月24日 星期五

[MATLAB] Convolution

This article explain clearly about convolution in discrete mathematics

and the matlab code.

You can have a check on this

2015年4月18日 星期六

[MATLAB]Generating Colour Image Using Matlab

http://stackoverflow.com/questions/19213354/generating-colour-image-using-matlab

2015年4月15日 星期三

[MATLAB] Combine 2 images into 1 image

http://stackoverflow.com/questions/4037779/how-to-combine-two-images-on-one-window-matlab

[MATLAB] 2014b making image sequences into avi movie file

clear all; % Clear all parameters
clc;
close all;  % Close all figures

%%

finf = dir(' file path\*.tif');   % *.tif => choose all tif file
n = length(finf);
data = cell(n,1);
len = zeros(n,1);

for k=1:n
    filename = [finf(k).name];
    data{k} = imread(filename);
    %F(k) = im2frame(data{k});
end

%%
%Making movie
writerObj  = VideoWriter('movie file path \ file_name.avi');
writerObj.FrameRate = 20;
open(writerObj);  %open movie file

for k=1:n
    img = rgb2gray(data{k});
    % Otsu's method
 
    level = graythresh(img);
    otsu = im2bw(img,level);
    otsu = im2uint8(otsu);

    new_img = [img otsu];  

    imshow(in_new_img);
    title('Otsu method');                      
 
    % binary to 8-bit integer
    mov = im2uint8(in_new_img);
 
    Mov = im2frame(mov); 
    writeVideo(writerObj,Mov);    
end

%%
% save as AVI file
close(writerObj);  %file name 


----------------------------------------
Official document for VideoWriter

2015年3月28日 星期六

[MATLAB] im2frame() colormap & Array Preallocation

There has some thing to notice is that im2frame need to assign a colormap

ie.  mov = im2frame(img_variable, colormap);

img_variable is the name of a image file that you are dealing with

colormap decide which kind of image you are using, like RGB color image or gray scale

imge etc.

So, next time don't forget to assign the colormap



Another thing is

when we want to make a video from a sequence of images

be careful this problem (Variable appears to change size on every loop iteration )

If not, you'll find out your RAM will overload when there are hundreds of images you

want to process.

(Related  1. Understanding Array Preallocation ;

                2. More about automatic array growth improvements in MATLAB R2011a

                3. Performance penalties)



2015年3月11日 星期三

[Matlab] Loading multiple images files and converting to movie

最近因為實驗上需要, 想使用 Matlab 讀取多張影像, 並將影像播放出來

首先, 需要克服的是如何讀取檔案的問題。

1. 讀取多張影像 / Load images into Matlab

(1) Loading multiple images files  (2)Matlab 中 Dir 的用法

Matlab 中提供了一個指令叫做 dir('path') ,  這邊的path需要提供明確的資料夾路徑位

置  Ex. C:\users\folder\

而後面如果要抓出特定的影像格式檔, 例如tiff檔, 則使用 *.tif

這邊的*是指所有為tif檔案格式的檔案

下面我從別人的博客借來的範例程式碼

fpath = dir('path\*.tif'); 
n = length(fpath); 
data = cell(n,1); 

for i=1:n 
 filename = ['path\',fpath(i).name]; 
 data{i} = imread(filename); 
end

for 迴圈裡面則是執行讀檔的動作

2.將影像轉成影片 / Convert images into movie

這邊 getframe 與 im2frame 這兩個指令可以使用(官方對於im2frame指令的說明)

將圖片存成一個序列檔

例如

imshow('1.tif'); 
F(1) = getframe; 

imshow('2.tif'); 
F(2) = getframe; 

... 

imshow('n.tif'); 
F(n) = getframe;

movie(F);

最後, Matlab 就會將數張影像進行播放, 達到播放影片般的效果


2014年12月25日 星期四

[MATLAB] Output matrix data to a Microsoft Excel(2013) file

If you want to output your image matrix (double type) to Microsoft Excel 2013 file

You should create a excel file first in a place in C disk of your computer first

And then use the following code like this:
filename_A = ' filepath\your_excel_filename.xlsx';
xlswrite( filename_A, Matrix name, sheet ); 
filepath is the file path of your excel file in your computer


Official document of xlswrite() command official_1 and official_2

Chinese version web tutorial here

Besides, this is the sheet of excel




2014年12月16日 星期二

2014年12月14日 星期日

[MATLAB] High frequency emphasis filtering Tutorial

Tutorial  here

http://www.ee.oulu.fi/research/imag/courses/dkk/exercises/2008/matlab/2/e2_h_emphasis.html

2014年12月9日 星期二

[MATLAB] HSV

1. A little description about HSV color space and simple matlab code. ( Link here )

2. Modeling a HSV color space  (Link here)

3. Visual HSV color histogram(Link here)

2014年12月8日 星期一

[MATLAB]Common command code

This article list all common command in MATLAB

But the most useful tool in MATLAB is using "help" and finding key word.

Hope it helps!

2014年11月27日 星期四

[MATLAB] Color image processing

Color is a very attractive issue in image processing

But what if i want to show a specific color ?


Maybe we can change traditional RGB color model 
to HSV color model 

Here is a simple solution on StackOverflow


They give a detailed solution and demonstration

=> How can I convert an RGB image to grayscale but keep one color?

Other article shows demonstration

2014年11月26日 星期三

[MATLAB] Adjusting subplot size

These two article in StackOverflow mentioned that :

How to adjust the picture size and position???

1. How can I set subplot size in MATLAB figure?

2. How do I position subplots in MATLAB?


But there is one thing we need to notice, not to use "i" or "j" as variable index.

Because in matlab, "i" or "j" might be seen as imaginary number of complex number.

( i or j = sqrt(-1) , ie. complex number c = a + bj or c = a+bi, a is real number part and b is imaginary part)

I hope it helps!

2014年11月25日 星期二

[MATLAB-GUI] Building a GUI program

The following link tells you how to make a Matlab GUI program

If there is a better tutorial, i will keep updating~


[MATLAB] Fast Fourier Transform algorithm

FFT is a very powerful tool for computer scientist

Here is other people's tutorial of this topic

Everyone who need to understand this should take a look at the following documents


/* 載入prettify的autoloader */ /* 載入JQuery */