2012年11月30日 星期五

matlab 根據顏色辨識圖像
















要辨識的圖像
可辨識出紅色部分與綠色部分


程式碼部分




clear all;
close all

inputName='beans.tiff';

img=imread(inputName);
R=img(:,:,1);
G=img(:,:,2);
B=img(:,:,3);

BW= 0.299*R+ 0.587*G + 0.114*B;

se=[0 1 0
    1 1 1
    0 1 0];

% tRed=150;
% tGreen=100;

% GBT= Global thresholding 用演算法算 threshold
tRed=reshape(R,size(BW,1)*size(BW,2),1);
tRed=gbt(tRed);

tGreen=reshape(G,size(BW,1)*size(BW,2),1);
tGreen=gbt(tGreen);


%製造畫圖空間
[rows, cols, colors] = size(img);
newimg = ones(rows, cols, colors);
imshow(newimg);
hold on




%若顏色小於定義值,則設為1

imR = zeros(size(R));
imR(G <tGreen & R>tRed) = 1;
imG = zeros(size(G));
imG(G >tGreen & R<tRed) = 1;

strResponse = input('please input morphological operations(q doing nothing): ', 's');
if strResponse=='o'
    imR = imopen(imR,se);
    imG = imopen(imG,se);
elseif strResponse=='c'
    imR = imclose(imR,se);
    imG = imclose(imG,se);
elseif strResponse=='q'
    break;
else
    fprintf('input error!! \n');
end

%畫出紅色部分
for i=1:size(BW,1)
    for j=1:size(BW,2)
        if imR(i,j)==1
            plot(j,i,'r');
            hold on
        end
    end
 
end

%畫出綠色部分
for i=1:size(BW,1)
    for j=1:size(BW,2)
        if imG(i,j)==1
            plot(j,i,'g');
            hold on
        end
    end
 
end







沒有留言:

張貼留言