MATLAB: Color filtration for Green, Brown, Orange, White and black

color filtration image processingyellow

Hi, i found this code to detect different colors in my input image. But it only detects red, blue and yellow. I want to know if someone ever seen this method to filter color, and if yes how can i had the other colors i want to find? The lines im talking about are:
%red if (ImgR(i,j,1)>=0.3) & (ImgR(i,j,2)<=0.45) & (ImgR(i,j,3)<=0.45)
%blue if (ImgB(i,j,1)<=0.45) & (ImgB(i,j,2)<=0.45) & (ImgB(i,j,3)>=0.2)
%yellow if (ImgY(i,j,1)>=0.6) & (ImgY(i,j,2)>=0.6) & (ImgY(i,j,3)<=0.3)
Here's the code :
function [Img] = ColorDt(InputImg,ColorInd)
%color filtration

%receipt of the image?
%InputImg=double(InputImg)./255;
[N, M, s]=size(InputImg);
% morphological image analysis
se=strel('disk',5); %diamond ball square disk
inImR=imerode(InputImg, se);
InputImg1=imreconstruct(inImR, InputImg);
InputImg=imdilate(InputImg1, se);
inIm=imreconstruct(imcomplement(InputImg), imcomplement(InputImg1));
InputImg=imcomplement(inIm);
%color filtration
if(ColorInd==1)
%figure,imshow(InputImg);
ImgR = InputImg;
for i=1:N
for j=1:M
%red
if (ImgR(i,j,1)>=0.3) & (ImgR(i,j,2)<=0.45) & (ImgR(i,j,3)<=0.45)
ImgR(i,j,1)=1;
ImgR(i,j,2)=1;
ImgR(i,j,3)=1;
else
ImgR(i,j,1)=0;
ImgR(i,j,2)=0;
ImgR(i,j,3)=0;
end;
end;
end;
%figure,imshow(ImgR)
Img = DelNoise(ImgR);
%figure,imshow(Img)

end;
if(ColorInd==2)
ImgB = InputImg;
for i=1:N
for j=1:M
%blue
if (ImgB(i,j,1)<=0.45) & (ImgB(i,j,2)<=0.45) & (ImgB(i,j,3)>=0.2)
ImgB(i,j,1)=1;
ImgB(i,j,2)=1;
ImgB(i,j,3)=1;
else
ImgB(i,j,1)=0;
ImgB(i,j,2)=0;
ImgB(i,j,3)=0;
end;
end;
end;
Img = DelNoise(ImgB);
%figure,imshow(Img)
end
if(ColorInd==3)
ImgY = InputImg;
for i=1:N
for j=1:M
%yellow
if (ImgY(i,j,1)>=0.6) & (ImgY(i,j,2)>=0.6) & (ImgY(i,j,3)<=0.3)
ImgY(i,j,1)=1;
ImgY(i,j,2)=1;
ImgY(i,j,3)=1;
else
ImgY(i,j,1)=0;
ImgY(i,j,2)=0;
ImgY(i,j,3)=0;
end;
end;
end;
Img = DelNoise(ImgY);
%figure,imshow(Img);
end
% figure,imshow(ImgR);
% figure,imshow(ImgB);
% figure,imshow(ImgY);
end

Best Answer

It looks like whoever wrote this is not familiar with the vectorized methods in MATLAB - this code is very inefficient. But anyway, all you have to do is to get rid of the "if" test for three distinct cases, and just change the numbers to whatever they are for whatever color you want.
if (InputImg(i,j,1)>=0.6) & (InputImg(i,j,2)>=0.6) & (InputImg(i,j,3)<=0.3) % Change these #'s
If you want to see a better, more flexible method, see the "Color segmentation by delta E color difference" in my File Exchange: http://www.mathworks.com/matlabcentral/fileexchange/?term=authorid%3A31862
Related Question