Saturday, October 23, 2010

An example of image processing using matlab

function [imgdatadb,mymask]=rgb2whiteblack(ImgFileName,mymask)
%  To show some basic image processing (percentage of some colors)
%  using matlab. Also shows how to create a mask using mouse.
%  Copyright: http://scriptdemo.blogspot.com
IsFig=0; IsFinalFig=1;
% read image
if nargin==0
    ImgFileName='8x.JPG';
end
if ~exist(ImgFileName,'file')
    disp(['image file: ',ImgFileName,' cannot be found!!! return nothing'])
    imgdatadb=[];mymask=[];
    return
end

% assume input image is in rgb mode
imgrgb=imread(ImgFileName);

% Be more accurate or professional, consider operations with rgb channels
if ~exist('mymask','var')
   %create the mask
   mask1=roipoly(imgrgb);
   mask2=roipoly(imgrgb);
   mask3=roipoly(imgrgb);
   mymask=mask1+mask2+mask3;
   close;
end

if IsFig % show rgb channels of the image
   figure;
   for N=1:4
       subplot(2,2,N);
       if N~=4
          imagesc(imgrgb(:,:,N));
       else
          imagesc(imgrgb);
       end
   end
end

% convert data into gray scale [intensity image]
imgdata=rgb2gray(imgrgb); % or maybe consider rgb2bw
%convert to double
imgdatadb=double(imgdata);

% convert dark part to black
imgdatadb(imgdatadb<100)=0;
% ..      light part to white
imgdatadb(imgdatadb>=100)=255;
% set mask region to specified value, e.g., 90
imgdatadb(mymask==1)=90;

% statistics
NumOfMaskP=length(find(mymask==1));
NumOfEffectiveP=length(imgdatadb(:))-NumOfMaskP;
PerEffective=NumOfEffectiveP/(NumOfMaskP+NumOfEffectiveP)*100;
PerBlack=length(find(imgdatadb==0))/NumOfEffectiveP*100;

% show percentage
disp(['Percentage of Effective  pixels (%): ',num2str(PerEffective)])
disp(['Percentage of black region (%): ',num2str(PerBlack)])

% show image
if IsFinalFig
   figure;
   title('Origin Gray image');imagesc(imgdata);
   figure;
   title('Black and White'); imagesc(uint8(imgdatadb));
end

No comments:

ShowCalendar