Edge Detection and Noise Filtering

  • Follow


I am working on an assessment with the target of producing .m file to perform edge detection on a selection of images...

There are four levels of implementation to apply:

1. To use “edge function” with the Canny, Sobel, Prewitt and LOG options 

2.To use convolution filtering with both the “imfilter” and standard convolution techniques to implement Sobel, and Roberts edge detection. 

3.To use a non linear or non convolution based technique to illustrate the application of “range” or“averaging” based edge detection. 

4.To use a non-linear region based statistical technique to analyse differences in local image
texture

The .m file should also allow a user (via inputs when calling the .m file(s) functions) to dynamically select the type of edge detection and the detection process applied 

I was wondering if anyone knows any good tutorials on the same subject or any resources to help me with this assessment??

Help would appreciated, thanks in advance !!
0
Reply Moey 2/3/2011 5:32:04 PM

Here's a demo I've posted here before.  Start with this:

% Demo to take the local mean, variance, and standard deviation
% of a gray scale image.
% userImage, if passed in, is used as the image.
% If userImage is not passed in, user is asked to use a demo image.
% Code written by ImageAnalyst
function local_variance(userImage)
% Clean up.
clc;    % Clear the command window.
close all;  % Close all figures (except those of imtool.)
workspace;  % Make sure the workspace panel is showing.

% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
% Don't use these lines if you're calling this from another m-file.
if(~isdeployed)
	cd(fileparts(which(mfilename)));
end

% Initialize.
fontSize = 20;
if nargin == 0
    % No image passed in on the command line.
    % Read in one of the standard MATLAB demo images
    % as our original gray scale image and display it.
    promptMessage = sprintf('Which image do you want to use.\nThe
coins or the cameraman?');
    button = questdlg(promptMessage, 'Select Image', 'Coins',
'Cameraman', 'Coins');
    if strcmp(button, 'Coins')
        grayImage = double(imread('coins.png')); % Cast to double.
    else
        grayImage = double(imread('cameraman.tif')); % Cast to double.
    end
else
    % Use the image array passed in on the command line.
    grayImage = double(userImage); % Cast to double.
end

% Start timing.
startTime = tic;

subplot(2, 3, 1);
imshow(grayImage, []);
title('Original Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.

% Blur the image with a 5 by 5 averaging (box filter) window.
blurredImage = conv2(grayImage, ones(5,5)/25);
subplot(2, 3, 2);
imshow(blurredImage, []);
title('Blurred Image', 'FontSize', fontSize);

% Perform a variance filter.
% Output image is the variance of the input image in a 3 by 3 sliding
window.
VarianceFilterFunction = @(x) var(x(:));
varianceImage = nlfilter(grayImage, [3 3], VarianceFilterFunction);
% An alternate way of doing the variance filter is on the next line:
% varianceImage = reshape(std(im2col(originalImage,[3 3],'sliding')),
size(originalImage)-2);
subplot(2, 3, 3);
imshow(varianceImage, [])
title('Variance Image', 'FontSize', fontSize);

% Compute the square root of the variance image to get the standard
deviation.
standardDeviationImage = sqrt(varianceImage);
subplot(2, 3, 4);
imshow(standardDeviationImage, [])
title('Standard Deviation Image', 'FontSize', fontSize);

% Compute the standard deviation filter with MATLAB's built-in
stdfilt() filter.
standardDeviationImage2 = stdfilt(grayImage);
subplot(2, 3, 5);
imshow(standardDeviationImage2, [])
title('Built-in stdfilt() filter', 'FontSize', fontSize);

% Perform Sobel filter
% h  = fspecial('sobel') returns a 3-by-3 filter h (shown below) that
emphasizes horizontal edges
% using the smoothing effect by approximating a vertical gradient.
% If you need to emphasize vertical edges, transpose the filter h'.
% [ 1  2  1
%   0  0  0
%  -1 -2 -1 ]
verticalSobelKernel = fspecial('sobel');
sobelImage = imfilter(grayImage, verticalSobelKernel);
subplot(2, 3, 6);
imshow(sobelImage, [])
title('Sobel edge filter', 'FontSize', fontSize);

elapsedTime = toc(startTime);
message = sprintf('Done!\n\nElapsed time = %.2f seconds.',
elapsedTime);
msgbox(message);
return; % End of local_variance() function.

0
Reply ImageAnalyst 2/3/2011 5:45:04 PM


Thanks for the reply, i am going through the demo to understand it.

One question, i have have tried to use this code:
button = questdlg('Which image do you want to use.', 'Choice', 'Square1', 'Square2', 'Square3', 'Peppers', 'Square1');
    
    if strcmp(button, 'Square1')
        UserImage = imread('square1.tiff'); 
        
    else if strcmp(button, 'Square2')
        UserImage = imread('square2.tif');
        
        else if strcmp(button, 'Square3')
        UserImage = imread('square3.tiff');
        
            else if strcmp(button, 'Peppers')
        UserImage = imread('peppers.tiff');
        
        end
        end
       end
    end 

But in the command window i get error which says too many input arguments!

I have alot of images where the user has to choose from....then how would i go on after that step to ask the user to choose an edge detection type i.e sobel , roberts etc

Thanks Again
0
Reply Moey 2/3/2011 7:31:05 PM

That's right.  You modified it to have 4 buttons.  But questdlg does
not allow 4 buttons.  Why don't you use uigetfile() instead?
0
Reply ImageAnalyst 2/3/2011 8:15:14 PM

Okay thanks for that option, i am in the process of using the help menu to make that operation work

Thanks
0
Reply Moey 2/3/2011 10:08:03 PM

I have set it up like this:

 [FileName,PathName] = uigetfile('*.tiff', 'Select An image');

then how to do tell matlab to process the image chosen by the user?

for example to apply the predefined operations after the image is chose..
0
Reply Moey 2/3/2011 10:41:03 PM

So far i got this:


UserImage = uigetfile('*.tiff', 'Select An image');
subplot(2,2,1); 
figure, imshow(UserImage); title('Original Image');


G = fspecial('gaussian',[3 3], 7);
Gaussian = imfilter(UserImage,G,'replicate');
subplot(2,2,2); 
figure, imshow(Gaussian); title('Gaussianed Image');

......!
0
Reply Moey 2/3/2011 10:49:03 PM

That's right.  Your UserImage is my "grayImage."  So then just
continue on from there.  I gave you a decent demo to start with, now
you take that and run with it.  I did the "hard" part (if you can call
it that) for you already.  Now it's your turn, especially since I
don't know what you want to do.  Do what I did, or do something else -
it's up to you and you now have the tools and the knowledge.
0
Reply ImageAnalyst 2/4/2011 12:36:26 AM

So far i got this:

startTime = tic;

[file path] = uigetfile({'*.tiff'}, 'Select An image');
A=imread(strcat(path,file));

% Checks that ima is a gray level image
if ndims(A) > 2 
    % then is it an RGB image? 
  if ndims(A) == 3
    A = rgb2gray(A); 
  else
      
      display('Strange format, I Cannot guarantee result');
 end    
end

%subplot(2,2,1); 
figure, imshow(A); title ('Original Image');


B = fspecial('disk',1);
BI = imfilter(A,B,'replicate');
%subplot(2,2,3); 
figure, imshow(BI); title('Blurred Image');


J = imnoise(BI,'salt & pepper',0.01);
figure, imshow(J); title('SnP');

K = filter2(fspecial('average',3),J)/255;
figure, imshow(K); title('average');

L = medfilt2(J,[3 3]);
figure, imshow(L); title('mean');


W1 = wiener2(L,[3 3], 5);
figure, imshow(W1); title('Noise removed');


button = questdlg('Which edge detection do you want to use?', 'Edge Detection Choice', 'Sobel', 'Canny', 'Prewitt', 'Sobel');
    
if strcmp(button, 'Sobel')
   P = edge(W1, 'sobel', 0.07);
       %some images work better with 0.05  
       %subplot
       figure, imshow(P); title('Sobel Edge Detection');

   else if strcmp(button, 'Canny')
            Can = edge(W1, 'canny', 0.4);
            %subplot
            figure, imshow(Can); title('Canny Edge Detection');
     
       else if strcmp(button, 'Prewitt')
               Pre = edge(W1, 'prewitt', 0.07);
                  %most work with 0.07
                  %specekle image 2 works best with the thresh as 0.12
                  %salt and pepper image one works best with thresh 0.13
                  %salt and pepper image two works best with thresh 0.10
                  %peppers image works best with thresh at 0.02
                  %subplot
               figure, imshow(Pre); title('Prewitt Edge Detection');
      
       end
     end
end 
   


elapsedTime = toc(startTime);
message = sprintf('Done!\n\nElapsed time = %.2f seconds.', elapsedTime);
msgbox(message);


Regarding that how far away would you say i am from fulfilling these steps?

1. To use “edge function” with the Canny, Sobel, Prewitt and LOG options 

2.To use convolution filtering with both the “imfilter” and standard convolution techniques to implement Sobel, and Roberts edge detection. 

3.To use a non linear or non convolution based technique to illustrate the application of “range” or“averaging” based edge detection. 

4.To use a non-linear region based statistical technique to analyse differences in local image
texture

......
0
Reply Moey 2/4/2011 11:39:04 PM

Moey:
You're getting there.  I didn't see the LOG or Robert process in there
though.  And I didn't see step 3 or 4.  You could just subtract the
blurred image from the original, and call rangfilt()  to do step 3.
What ideas do you have for step 4?
0
Reply ImageAnalyst 2/5/2011 1:37:01 AM

ImageAnalyst :

I am in the process of replacing the blurred image and replace it with the rangfilt()..

well i am very vague on step 4. i dont understand much from it but following a tutorial we did in class follows as:

-Creating a blank memory
-Then create two buffers to compare using a mask 3x3
-Then use the operator myoffset to extract the image pixels for the 1st column of the mask then the middle then 3rd column
-Then compute the statistics

Well thats what i got form the tutorial but applying it in my application is whole different story lol
0
Reply Moey 2/5/2011 2:59:04 PM

It does seem somewhat vague.
For the first one, use zeros()
For the second one, I guess it simply means that you have two images,
like you read in using imread(0 or something.
The third one is confusing.  I know it wants a 3x3 kernal/window/mask
but why it's talking about doing things column by column instead of
just operating on the entire mask, I have no idea.
For the 4th one, this could be just like doing what I already told you
- taking the standard deviation or variance of the local window as it
scans along your image.

0
Reply ImageAnalyst 2/5/2011 4:07:57 PM

Regarding step 4, i will post the code we did in the tutorial (which surprisingly didn't work for me)
 but regarding what you said about subtracting the blurred image form the original, i am looking at ur demo and i got:

blurredImage = conv2(double(A), ones(5,5)/25);
figure, imshow(blurredImage, []); title('Blurred Image')

to blur the image, then i am vague on the step of taking the outcome and subtracting it from the original...do use a filter here to do that ?
0
Reply Moey 2/5/2011 4:41:03 PM

Just do
differenceImage = double(grayImage) - double(blurredImage);
You need to cast to double to get the negative values, otherwise it
will clip all those at 0 if the images are uint8.
0
Reply ImageAnalyst 2/5/2011 5:18:09 PM

Well i tried that i get an error message stating :

??? Error using ==> minus
Matrix dimensions must agree.

Error in ==> Test3 at 27
differenceImage = double(A) - double(B);

I did some research and the i used the operator:

[rmax, cmax] = size(A)

[rmax, cmax] = size(B)

to find some stats on the images and 

A=  650, 650
B= 654,654

and the minus function wont work because they have different stats, so i researched again to slove that but i havent came across anything that helps!!

so i am here again to ask for your help.....
0
Reply Moey 2/5/2011 6:52:03 PM

If you used the conv2() function, make sure you used the 'same' option
because otherwise, convolution will enlarge the image.  If it's bigger
because of some other reason, you'll have to figure that out.
0
Reply ImageAnalyst 2/5/2011 7:04:41 PM

Regarding step 4, here is the code we did in the tutorial but when i run it MATLAB says busy and nothing hapens:



tic

I = imread('shapes_gaussian_1.tiff');
figure, imshow(I);

[nr, nc] = size(I);

opimage = [nr,nc];

mybuffer(9) = 0;

myoffset = uint16(1);
counter = 1;

for k = (1+myoffset):(nr-myoffset)
    
    for l = (1+myoffset):(nc-myoffset)
        
        mybuffer(counter) = I((k-myoffset),(l-myoffset));
        counter = counter+1;
        
        mybuffer(counter) = I((k),(l-myoffset));
        counter = counter+1;
        
        mybuffer(counter) = I((k+myoffset),(l-myoffset));
        counter = counter+1;
        
        
        
        mybuffer(counter) = I((k-myoffset),(l));
        counter = counter+1;
        
         
        mybuffer(counter) = I((k),(l));
        counter = counter+1;
        
        mybuffer(counter) = I((k+myoffset),(l));
        counter = counter+1;
        
        
        
        mybuffer(counter) = I((k-myoffset),(l+myoffset));
        counter = counter+1;
        
         mybuffer(counter) = I((k),(l+myoffset));
        counter = counter+1;
        
         mybuffer(counter) = I((k+myoffset),(l+myoffset));
        counter = counter+1;
        
        
        buffmin = min(mybuffer);
        buffmax = max(mybuffer);
        
        opimage(k,l) = (buffmax - buffmin);
        
    end
end

figure, imshow(uint8((opimage)));

toc
0
Reply Moey 2/7/2011 8:09:03 PM

I don't know.  What happens when you step through it with the debugger?
0
Reply ImageAnalyst 2/8/2011 1:04:51 AM

Sorry i havent replied for a while, i have been so busy some some other assessments..all the other images are goin fine but theres one time thats hard

[IMG]http://i785.photobucket.com/albums/yy137/imoey_photo/image%20processing/Face.jpg[/IMG]

so far i started a different m file for it:

[file path] = uigetfile({'*.tiff'}, 'Select An image');

A = double(imread(strcat(path,file)));

% Checks that ima is a gray level image
if ndims(A) > 2 
    % then is it an RGB image? 
  if ndims(A) == 3
    A = rgb2gray(A); 
  else
      
      display('Strange format, I Cannot guarantee result');
 end    
end
%subplot(2,2,1); 
figure, imshow(A, []); title ('Original Image');


S = fspecial('unsharp');
sharpened = imfilter(A,S,'replicate');
%subplot(2,2,4); 
figure, imshow(sharpened); title('Sharpened Image');

B = fspecial('disk',1);
BI = imfilter(sharpened,B,'replicate');
%subplot(2,2,3); 
figure, imshow(BI); title('Blurred Image');

Then i am stuck !!
0
Reply avirex_2 (7) 2/14/2011 6:26:04 PM

On Feb 14, 1:26=A0pm, "Moey Makki" <avire...@msn.com> wrote:
> Sorry i havent replied for a while, i have been so busy some some other a=
ssessments..all the other images are goin fine but theres one time thats ha=
rd
>
> [IMG]http://i785.photobucket.com/albums/yy137/imoey_photo/image%20process=
i...[/IMG]
>
[snip]
> Then i am stuck !!
---------------------------------------------------------------------------=
-
Moey Makki:
This doesn't look like the kind of image you can use edge detection on
because the edges are not in intensity - they are in texture.  You
will need to do texture segmentation with this image.  Go here for
algorithms:
http://iris.usc.edu/Vision-Notes/bibliography/contentstwod.html#2-D%20Featu=
re%20Analysis,%20Extraction%20and%20Representations,%20Shape,%20Skeletons,%=
20Texture

ImageAnalyst
0
Reply imageanalyst (7590) 2/14/2011 7:44:49 PM

Okay thanks, i will check it out now...

One more thing, because i am offering the user a various number of edge detection and questdlg only gives 3 buttons..

i though of naming an m file for each edge detection and the user can call each edge detection in the command window with the desired number and the images will be saved in a folder..

now for the hard part coding all that...

i named the m file function Assessment2, 
but then i don't kno how to go about it!!

Thanks
0
Reply avirex_2 (7) 2/14/2011 8:00:04 PM

Moey Makki:
Here's a snippet from my custom-shaped histogram application:
http://www.mathworks.com/matlabcentral/fileexchange/28972-custom-shaped-histogram

where you can select one of three options.  Adapt it in the obvious
ways:
	message = sprintf('Which demo image do you want to use?');
	selectedImage = questdlg(message, 'Which Demo Image?', 'Chicago
Skyline', 'Ford Shelby Car', 'Woman on Beach', 'Chicago Skyline');
	if strcmp(selectedImage, 'Chicago Skyline')
	 	baseFileName = 'chicago_skyline_small.png';
		demoImage = 1;
	elseif strcmp(selectedImage, 'Ford Shelby Car')
		baseFileName = '2011_Ford_Shelby_GT500.png';
		demoImage = 2;
	else
		baseFileName = 'Beach_Woman.png';
		demoImage = 3;
	end

To call m-files that are different files, simply call them by name
with the arguments listed in between the parentheses.  For example

[output1 output2] = MyFunction(inputArg1, inputArg2, inputArg3);

Not hard.  Just make sure you always supply all output arguments.
This is best done by assigning them to null or some default at the top
of the function because sometimes people assign them inside an if
statement and it never gets assigned and then errors out.  It is also
professional to catch your own errors using try/catch to try to handle
them gracefully and not have it just barf up a bunch of red gibberish
all over the command window which will confuse and anger your user.
0
Reply imageanalyst (7590) 2/14/2011 10:26:17 PM

I have managed to make the function work when being called from the command window:

function Myedge(I, Type, thresh)

i have specified I as the image, Type as the edge function, 

but i am dont know how to specify thresh that affects the edge detection...

How do i tell matlab to take the amount of thresh hold applied by the user and apply to the edge detection function....
0
Reply avirex_2 (7) 2/16/2011 5:04:04 PM

On Feb 16, 12:04=A0pm, "Moey Makki" <avire...@msn.com> wrote:
> I have managed to make the function work when being called from the comma=
nd window:
>
> function Myedge(I, Type, thresh)
>
> i have specified I as the image, Type as the edge function,
>
> but i am dont know how to specify thresh that affects the edge detection.=
...
>
> How do i tell matlab to take the amount of thresh hold applied by the use=
r and apply to the edge detection function....

-------------------------------------------------------------------------
Why don't you just use my thresholding app:
http://www.mathworks.com/matlabcentral/fileexchange/authors/31862
0
Reply imageanalyst (7590) 2/16/2011 6:04:31 PM

Its aright i have figured it out and it wasnt that hard lol..

over all i think i am more or less donish!

function Myedge(EdgeType, userthresh)

%I = imread(imgname);
%figure, imshow(I); title('Original Image');

[file path] = uigetfile({'*.tiff'}, 'Select An image');
I=imread(strcat(path,file));

% Checks that ima is a gray level image
if ndims(I) > 2 
    % then is it an RGB image? 
  if ndims(I) == 3
      
    A = rgb2gray(I); 
  else
      
      display('Strange format, I Cannot guarantee result');
 end    
end

figure, imshow(I); title('Original Image');


B = fspecial('disk',1);
BI = imfilter(I,B,'replicate');
%subplot(2,2,3); 
figure, imshow(BI); title('Blurred Image');


J = imnoise(BI,'salt & pepper',0.01);
figure, imshow(J); title('SnP');

K = filter2(fspecial('average',3),J)/255;
figure, imshow(K); title('average');

L = medfilt2(J,[3 3]);
figure, imshow(L); title('mean');



W1 = wiener2(L,[3 3], 5);
figure, imshow(W1); title('Noise removed');


switch EdgeType
    
    case 'sobel', (edge(W1, 'sobel', userthresh));
    case 'canny', (edge(W1, 'canny', userthresh));
    case 'prewitt', (edge(W1, 'prewitt', userthresh));
    case 'roberts', (edge(W1, 'roberts', userthresh));
    case 'log', (edge(W1, 'log', userthresh));
 
end


%Type = edge(W1,'canny', userthresh);
%figure, imshow(Type); title('Canny Edge Detection');
%imwrite(Type, 'Canny Edge Detection.tiff');

end
0
Reply avirex_2 (7) 2/16/2011 6:05:05 PM

I am making a seprate m file that reads in multiple images and dose the operations and saves the results in a folder..

am i right in starting witth:


files = dir('*.tiff');

for i=1:length(files)

img = imread(files(i).name);

end


if ndims(img{i}) > 2 
    % then is it an RGB image? 
  if ndims(img{i}) == 3
      
    A = rgb2gray(img{i}); 
  else
      
      display('Strange format, I Cannot guarantee result');
 end    
end

figure, imshow(img{2}); title('Original Image');
0
Reply avirex_2 (7) 2/17/2011 7:52:03 PM

On Feb 17, 2:52=A0pm, "Moey Makki" <avire...@msn.com> wrote:
> I am making a seprate m file that reads in multiple images and dose the o=
perations and saves the results in a folder..
>
> am i right in starting witth:
>
> files =3D dir('*.tiff');
>
> for i=3D1:length(files)
>
> img =3D imread(files(i).name);
>
> end
>
> if ndims(img{i}) > 2
> =A0 =A0 % then is it an RGB image?
> =A0 if ndims(img{i}) =3D=3D 3
>
> =A0 =A0 A =3D rgb2gray(img{i});
> =A0 else
>
> =A0 =A0 =A0 display('Strange format, I Cannot guarantee result');
> =A0end =A0 =A0
> end
>
> figure, imshow(img{2}); title('Original Image');

-------------------------------------------------
No.  You're reusing the (bad name) of "i" each time, so you don't need
the braces since i is not a cell array.
0
Reply imageanalyst (7590) 2/17/2011 7:56:12 PM

> No.  You're reusing the (bad name) of "i" each time, so you don't need
> the braces since i is not a cell array.


so instead of img{i}  its just stays img
0
Reply avirex_2 (7) 2/17/2011 8:05:04 PM

On Feb 17, 3:05=A0pm, "Moey Makki" <avire...@msn.com> wrote:
> > No. =A0You're reusing the (bad name) of "i" each time, so you don't nee=
d
> > the braces since i is not a cell array.
>
> so instead of img{i} =A0its just stays img

Yes.
0
Reply imageanalyst (7590) 2/17/2011 8:20:26 PM

Okay,

lets say i want to view a certain image... i am guessing its not 

figure, imshow(img4)
0
Reply avirex_2 (7) 2/17/2011 9:21:04 PM

On Feb 17, 4:21=A0pm, "Moey Makki" <avire...@msn.com> wrote:
> Okay,
>
> lets say i want to view a certain image... i am guessing its not
>
> figure, imshow(img4)

-------------------------------
No, it would be
imshow(img);

Here, look at this demo where I get all the files in a folder and then
convert them to hsv color space, and histogram and display the hsv
histograms.

% IMPORTANT: The newsreader may break long lines into multiple lines.
% Be sure to join any long lines that got split into multiple single
lines.
% These can be found by the red lines on the left side of your
% text editor, which indicate syntax errors, or else just run the
% code and it will stop at the split lines with an error.

function rgb2hsv_Demo()

% Change the current folder to the folder of this m-file.
if(~isdeployed)
	cd(fileparts(which(mfilename)));
end
clc;	% Clear command window.
clear;	% Delete all variables.
close all;	% Close all figure windows except those created by imtool.
imtool close all;	% Close all figure windows created by imtool.
workspace;	% Make sure the workspace panel is showing.
fontSize =3D 14;

try
% Read in standard MATLAB color demo images.
imagesFolder =3D 'C:\Program Files\MATLAB\R2010a\toolbox\images
\imdemos';
if ~exist(imagesFolder, 'dir')
 	message =3D sprintf('Please browse to your image folder');
	button =3D questdlg(message, 'Specify Folder', 'OK', 'Cancel', 'OK');
	drawnow;	% Refresh screen to get rid of dialog box remnants.
	if strcmpi(button, 'Cancel')
	   return;
	else
		imagesFolder =3D uigetdir();
		if imagesFolder =3D=3D 0
			return;
		end
	end
end

% Read the directory to get a list of images.
filePattern =3D [imagesFolder, '\*.jpg'];
jpegFiles =3D dir(filePattern);
filePattern =3D [imagesFolder, '\*.tif'];
tifFiles =3D dir(filePattern);
filePattern =3D [imagesFolder, '\*.png'];
pngFiles =3D dir(filePattern);
filePattern =3D [imagesFolder, '\*.bmp'];
bmpFiles =3D dir(filePattern);
imageFiles =3D [jpegFiles; tifFiles; pngFiles; bmpFiles];

% Bail out if there aren't any images in that folder.
numberOfImagesProcessed =3D 0;
numberOfImagesToProcess =3D length(imageFiles);
if numberOfImagesToProcess <=3D 0
 	message =3D sprintf('I did not find any JPG, TIF, PNG, or BMP images
in the folder\n%s\nClick OK to Exit.', imagesFolder);
	uiwait(msgbox(message));
	return;
end

% Create a figure for our images.
figure;
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')

% Preallocate arrays to hold the means of all the images.
hImage_Mean =3D zeros(numberOfImagesToProcess, 1);
sImage_Mean =3D zeros(numberOfImagesToProcess, 1);
vImage_Mean =3D zeros(numberOfImagesToProcess, 1);
% Loop though all images, converting to hsv
% and then getting the means of the h, s, and v channels.
for k =3D 1 : numberOfImagesToProcess
	% Read in this one file.
	baseFileName =3D imageFiles(k).name;
	fullFileName =3D fullfile(imagesFolder, baseFileName);
	rgbImage =3D imread(fullFileName);
	[rows columns numberOfColorBands] =3D size(rgbImage);
	if numberOfColorBands <=3D 1
		% Skip monochrome or indexed images.
		continue;
	end
	subplot(3, 3, 1);
	imshow(rgbImage, []);
	[rows columns numberOfColorBands] =3D size(rgbImage);
	caption =3D sprintf('Original Color Image\n%s\n%d rows by %d columns by
%d color channels', ...
		baseFileName, rows, columns, numberOfColorBands);
	% If there are underlines in the name, title() converts the next
character to a subscript.
	% To avoid this, replace underlines by spaces.
	caption =3D strrep(caption, '_', ' ');
	title(caption, 'FontSize', fontSize);
	drawnow;  % Force it to update, otherwise it waits until after the
conversion to double.

	% Convert to floating point so it does the calculations correctly.
	% Also needs to be normalized to 0-1.
	rgbFloating =3D double(rgbImage) / 255.0;

	% Compute hsv image
	hsvImage =3D rgb2hsv(rgbFloating);
	% H image:
	hImage =3D hsvImage(:,:,1);
	subplot(3, 3, 4);
	imshow(hImage, []); % Display the image.
	% Compute mean
	hImage_Mean(k) =3D mean(hImage(:));
	caption =3D sprintf('Hue Image.  Mean =3D %6.2f', hImage_Mean(k));
	title(caption, 'FontSize', fontSize);
	% Compute and display the histogram for the H image.
	histogramDouble(hImage, 7, 'Histogram of Hue Image');

	% S image:
	sImage =3D hsvImage(:,:,2);
	subplot(3, 3, 5);
	imshow(sImage, []); % Display the image.
	% Compute mean
	sImage_Mean(k) =3D mean(sImage(:));
	caption =3D sprintf('Saturation Image.  Mean =3D %6.2f', sImage_Mean(k));
	title(caption, 'FontSize', fontSize);
	% Compute and display the histogram for the S image.
	histogramDouble(sImage, 8, 'Histogram of Saturation Image');

	% V image:
	vImage =3D hsvImage(:,:,3);
	subplot(3, 3, 6);
	imshow(vImage, []); % Display the image.
	numberOfImagesProcessed =3D numberOfImagesProcessed + 1;
	% Compute mean
	vImage_Mean(k) =3D mean(vImage(:));
	caption =3D sprintf('Value Image.  Mean =3D %6.2f', vImage_Mean(k));
	title(caption, 'FontSize', fontSize);
	% Compute and display the histogram for the V image.
	histogramDouble(vImage, 9, 'Histogram of Value Image');

	% Prompt user to continue, unless they're at the last image.
	if k < numberOfImagesToProcess
		promptMessage =3D sprintf('Currently displaying image #%d of %d:\n%s\n
\nDo you want to\nContinue processing, or\nCancel processing?',...
			numberOfImagesProcessed, numberOfImagesToProcess, baseFileName);
		button =3D questdlg(promptMessage, 'Continue?', 'Continue', 'Cancel',
'Continue');
		if strcmp(button, 'Cancel')
			break;
		end
	end
end
% Crop off any unassigned values:
hImage_Mean =3D hImage_Mean(1:numberOfImagesProcessed);
sImage_Mean =3D sImage_Mean(1:numberOfImagesProcessed);
vImage_Mean =3D vImage_Mean(1:numberOfImagesProcessed);

% Print to command window
fprintf(1, '                Filename,   H Mean, S Mean, V Mean\n');
for k =3D 1 : length(hImage_Mean)
	baseFileName =3D imageFiles(k).name;
	fprintf(1, '%24s    %6.2f, %6.2f, %6.2f\n', ...
		baseFileName, hImage_Mean(k), sImage_Mean(k), vImage_Mean(k));
end

if numberOfImagesProcessed =3D=3D 1
	caption =3D sprintf('Done with demo!\n\nProcessed 1 image.\nCheck out
the command window for the results');
else
	caption =3D sprintf('Done with demo!\n\nProcessed %d images.\nCheck out
the command window for the results', numberOfImagesProcessed);
end
msgbox(caption);
catch ME
	errorMessage =3D sprintf('Error in function rgb2hsv_demo.\nPerhaps the
image is too large.\n\nError Message:\n%s', ME.message);
	uiwait(warndlg(errorMessage));
end


function histogramDouble(dblImage, subplotNumber, caption)
	% So now we have a double image that is our "starting image."
	% However can't use imhist on this.  We need to scale to 0-1.
	minValue =3D min(min(dblImage));
	maxValue =3D max(max(dblImage));
	range =3D maxValue - minValue;
	dblImage =3D (dblImage - minValue) / range;
	% Check to verify that range is now 0-1.
% 	minValueNorm =3D min(min(dblImage));
% 	maxValueNorm =3D max(max(dblImage));

	% Let's get its histogram into 256 bins.
	[pixelCount grayLevels] =3D imhist(dblImage, 256);

	% Let's suppress the zero bin because it's always so high.
	pixelCount(1) =3D 0;

	% But now grayLevelsD goes from 0 to 1.
	% We want it to go from the original range, so we need to scale.
	originalDoubleGrayLevels =3D range * grayLevels + minValue;

	subplot(3, 3, subplotNumber);
	plot(originalDoubleGrayLevels, pixelCount);
	title(caption, 'FontSize', 14);
	% Scale x axis manually.
	xlim([originalDoubleGrayLevels(1) originalDoubleGrayLevels(end)]);
	return;

0
Reply imageanalyst (7590) 2/17/2011 11:42:27 PM

In article <f00ac326-169a-4431-89bc-804beb621fa1@e8g2000vbz.googlegroups.com>,
ImageAnalyst  <imageanalyst@mailinator.com> wrote:
>Here, look at this demo where I get all the files in a folder and then
>convert them to hsv color space, and histogram and display the hsv
>histograms.
>[...]
>function rgb2hsv_Demo()
>[...]

Nice work, ImageAnalyst!

Francis
0
Reply fburton 2/18/2011 2:27:17 PM

hi
i m working on voice activity detection in simulink using zero crossing rate technique.can any of you plz guide me.i m stuck to implementit on simulink



its m-file is




function speech=vad(x)
persistent enframe;

%x=double(x);
x=x/max(abs(x));


FrameLen=300;
FrameInc=100;

amp1=40;
amp2=10;
zcr1=10;
zcr2=5;

maxsilence=3; % 3*10ms=30ms
minlen=15;    % 15*10ms=150ms
status=0;
count=0;
silence=0;


tmp1=enframe(x(1:length(x)-1),FrameLen,FrameInc);
tmp2=enframe(x(2:length(x)),FrameLen,FrameInc);
signs=(tmp1.*tmp2)<0;
diffs=(tmp1-tmp2)>0.05;       
zcr=sum(signs.*diffs,2);


amp=sum(abs(enframe(filter([1 0.9375],1,x),FrameLen,FrameInc)),2);


amp1=min(amp1,max(amp));  
amp2=min(amp2,max(amp)/3);


x1=0;
x2=0;
for n=1:length(zcr)
    goto=0;
    switch status
        case {0,1}              
            if amp(n)>amp1       
                x1=max(n-count-1,1);
                status=2;
                silence=0;
                count=count+1;
            elseif amp(n)>amp2|zcr(n)>zcr2 
                status=1;
                count=count+1;
            else                
                status=0;
                count=0;
            end
        case 2,                 
            if amp(n)>amp2|zcr(n)>zcr2     
                count=count+1;
            else               
                silence=silence+1;
                if silence<maxsilence      
                    count=count+1;
                elseif count<minlen       
                    status=0;
                    silence=0;
                    count=0;
                else
                    status=3;
                end
            end
        case 3,
            break;
    end
end

count=count-silence/2;
x2=x1+count-1;

% subplot(311)
% plot(x);
% axis([1 length(x) -1 1]);
% ylabel('Speech');
% line([x1*FrameInc,x1*FrameInc],[-1,1],'Color','red');
% line([x2*FrameInc,x2*FrameInc],[-1,1],'Color','red');
speech=x(x1*FrameInc:x2*FrameInc);
% sound(speech,8000);

% subplot(312)
% plot(amp)
% axis([1 length(amp) 0 max(amp)])
% ylabel('Energy');
% line([x1,x1],[min(amp),max(amp)],'Color','red');
% line([x2,x2],[min(amp),max(amp)],'Color','red');

% subplot(313)
% plot(zcr)
% axis([1 length(zcr) 0 max(zcr)])
% ylabel('ZCR');
% line([x1,x1],[min(zcr),max(zcr)],'Color','red');
% line([x2,x2],[min(zcr),max(zcr)],'Color','red');

%figure(2);plot(speech);
0
Reply karoot 2/24/2011 3:13:04 AM

i m doing VAD based on zero crossing rate.i have studied papers and come to know that zero crossing rate threshold is


ZCRT=mean(noise)+5*standard deviation(noise)


how can i set value of detection?how can i implement ZCR in SIMULINK?
is there any other method? 



its mfile is


function [w]=vad(x)



x=double(x);
x=x/max(abs(x));

%&#24120;&#25968;&#35774;&#32622;
framelen=256;
framelnc=100;

amp1=10;
amp2=2;
zcr1=10;
zcr2=5;

maxsilence=3;%3*10ms=30ms
minlen=15; %15*10ms=150ms
status=0;
count=0;
silence=0;


tmp1=enframe(x(1:length(x)-1),framelen,framelnc);
tmp2=enframe(x(2:length(x)),framelen,framelnc);
signs=(tmp1.*tmp2)<0;
diffs=(tmp1-tmp2)>0.02;
zcr=sum(signs.*diffs,2);

%&#35745;&#31639;&#30701;&#26102;&#33021;&#37327;
amp=sum(abs(enframe(filter([1 -0.9375],1,x),framelen,framelnc)),2)

%&#35843;&#25972;&#33021;&#37327;&#38376;&#38480;
amp1=min(amp1,max(amp)/4);
amp2=min(amp2,max(amp)/8);

%&#24320;&#22987;&#31471;&#28857;&#26816;&#27979;
x1=0;
x2=0;
for n=1:length(zcr)
goto=0;
switch status
case {0,1}
if amp(n)>amp1 %&#30830;&#20449;&#36827;&#20837;&#35821;&#38899;&#27573;
x1=max(n-count-1,1);
status=2;
silence=0;
count=count+1;
elseif amp(n)>amp2 | zcr(n)>zcr2 %&#21487;&#33021;&#22788;&#20110;&#35821;&#38899;&#27573;
status=1;
count=count+1;
else
status=0;
count=0;
end
case 2, %2&#65309;&#35821;&#38899;&#27573;
if amp(n)>amp2 | zcr(n)>zcr2 %&#20445;&#25345;&#22312;&#35821;&#38899;&#27573;
count=count+1;
else
silence=silence+1;
if silence<maxsilence
count=count+1;
elseif count<minlen
status=0;
silence=0;
count=0;
else
status=3;
end
end
case 3,
break;
end
end

count=count-silence/2;
x2=x1+count-1;
subplot(1,1,1)
plot(x)

w=x(x1*framelnc:x2*framelnc,:);
figure(2)
plot(w)
0
Reply karoot 2/24/2011 5:44:04 AM

33 Replies
217 Views

(page loaded in 0.337 seconds)

Similiar Articles:


















7/18/2012 3:43:35 AM


Reply: