Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Edge Detection and Noise Filtering

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 3 Feb, 2011 17:32:04

Message: 1 of 34

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 !!

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 3 Feb, 2011 17:45:04

Message: 2 of 34

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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 3 Feb, 2011 19:31:05

Message: 3 of 34

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

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 3 Feb, 2011 20:15:14

Message: 4 of 34

That's right. You modified it to have 4 buttons. But questdlg does
not allow 4 buttons. Why don't you use uigetfile() instead?

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 3 Feb, 2011 22:08:03

Message: 5 of 34

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

Thanks

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 3 Feb, 2011 22:41:03

Message: 6 of 34

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..

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 3 Feb, 2011 22:49:03

Message: 7 of 34


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');

.....!

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 4 Feb, 2011 00:36:26

Message: 8 of 34

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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 4 Feb, 2011 23:39:04

Message: 9 of 34

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

.....

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 5 Feb, 2011 01:37:01

Message: 10 of 34

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?

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 5 Feb, 2011 14:59:04

Message: 11 of 34

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

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 5 Feb, 2011 16:07:57

Message: 12 of 34

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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 5 Feb, 2011 16:41:03

Message: 13 of 34

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 ?

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 5 Feb, 2011 17:18:09

Message: 14 of 34

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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 5 Feb, 2011 18:52:03

Message: 15 of 34

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.....

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 5 Feb, 2011 19:04:41

Message: 16 of 34

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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 7 Feb, 2011 20:09:03

Message: 17 of 34

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

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 8 Feb, 2011 01:04:51

Message: 18 of 34

I don't know. What happens when you step through it with the debugger?

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 14 Feb, 2011 18:26:04

Message: 19 of 34

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 !!

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 14 Feb, 2011 19:44:49

Message: 20 of 34

On Feb 14, 1:26 pm, "Moey Makki" <avire...@msn.com> wrote:
> 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%20processi...[/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%20Feature%20Analysis,%20Extraction%20and%20Representations,%20Shape,%20Skeletons,%20Texture

ImageAnalyst

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 14 Feb, 2011 20:00:04

Message: 21 of 34

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

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 14 Feb, 2011 22:26:17

Message: 22 of 34

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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 16 Feb, 2011 17:04:04

Message: 23 of 34

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....

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 16 Feb, 2011 18:04:31

Message: 24 of 34

On Feb 16, 12:04 pm, "Moey Makki" <avire...@msn.com> wrote:
> 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....

-------------------------------------------------------------------------
Why don't you just use my thresholding app:
http://www.mathworks.com/matlabcentral/fileexchange/authors/31862

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 16 Feb, 2011 18:05:05

Message: 25 of 34

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

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 17 Feb, 2011 19:52:03

Message: 26 of 34

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');

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 17 Feb, 2011 19:56:12

Message: 27 of 34

On Feb 17, 2:52 pm, "Moey Makki" <avire...@msn.com> wrote:
> 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');

-------------------------------------------------
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.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 17 Feb, 2011 20:05:04

Message: 28 of 34


> 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

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 17 Feb, 2011 20:20:26

Message: 29 of 34

On Feb 17, 3:05 pm, "Moey Makki" <avire...@msn.com> wrote:
> > 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

Yes.

Subject: Edge Detection and Noise Filtering

From: Moey Makki

Date: 17 Feb, 2011 21:21:04

Message: 30 of 34

Okay,

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

figure, imshow(img4)

Subject: Edge Detection and Noise Filtering

From: ImageAnalyst

Date: 17 Feb, 2011 23:42:27

Message: 31 of 34

On Feb 17, 4:21 pm, "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 = 14;

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

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

% Bail out if there aren't any images in that folder.
numberOfImagesProcessed = 0;
numberOfImagesToProcess = length(imageFiles);
if numberOfImagesToProcess <= 0
  message = 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 = zeros(numberOfImagesToProcess, 1);
sImage_Mean = zeros(numberOfImagesToProcess, 1);
vImage_Mean = zeros(numberOfImagesToProcess, 1);
% Loop though all images, converting to hsv
% and then getting the means of the h, s, and v channels.
for k = 1 : numberOfImagesToProcess
% Read in this one file.
baseFileName = imageFiles(k).name;
fullFileName = fullfile(imagesFolder, baseFileName);
rgbImage = imread(fullFileName);
[rows columns numberOfColorBands] = size(rgbImage);
if numberOfColorBands <= 1
% Skip monochrome or indexed images.
continue;
end
subplot(3, 3, 1);
imshow(rgbImage, []);
[rows columns numberOfColorBands] = size(rgbImage);
caption = 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 = 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 = double(rgbImage) / 255.0;

% Compute hsv image
hsvImage = rgb2hsv(rgbFloating);
% H image:
hImage = hsvImage(:,:,1);
subplot(3, 3, 4);
imshow(hImage, []); % Display the image.
% Compute mean
hImage_Mean(k) = mean(hImage(:));
caption = sprintf('Hue Image. Mean = %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 = hsvImage(:,:,2);
subplot(3, 3, 5);
imshow(sImage, []); % Display the image.
% Compute mean
sImage_Mean(k) = mean(sImage(:));
caption = sprintf('Saturation Image. Mean = %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 = hsvImage(:,:,3);
subplot(3, 3, 6);
imshow(vImage, []); % Display the image.
numberOfImagesProcessed = numberOfImagesProcessed + 1;
% Compute mean
vImage_Mean(k) = mean(vImage(:));
caption = sprintf('Value Image. Mean = %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 = sprintf('Currently displaying image #%d of %d:\n%s\n
\nDo you want to\nContinue processing, or\nCancel processing?',...
numberOfImagesProcessed, numberOfImagesToProcess, baseFileName);
button = questdlg(promptMessage, 'Continue?', 'Continue', 'Cancel',
'Continue');
if strcmp(button, 'Cancel')
break;
end
end
end
% Crop off any unassigned values:
hImage_Mean = hImage_Mean(1:numberOfImagesProcessed);
sImage_Mean = sImage_Mean(1:numberOfImagesProcessed);
vImage_Mean = vImage_Mean(1:numberOfImagesProcessed);

% Print to command window
fprintf(1, ' Filename, H Mean, S Mean, V Mean\n');
for k = 1 : length(hImage_Mean)
baseFileName = 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 == 1
caption = sprintf('Done with demo!\n\nProcessed 1 image.\nCheck out
the command window for the results');
else
caption = sprintf('Done with demo!\n\nProcessed %d images.\nCheck out
the command window for the results', numberOfImagesProcessed);
end
msgbox(caption);
catch ME
errorMessage = 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 = min(min(dblImage));
maxValue = max(max(dblImage));
range = maxValue - minValue;
dblImage = (dblImage - minValue) / range;
% Check to verify that range is now 0-1.
% minValueNorm = min(min(dblImage));
% maxValueNorm = max(max(dblImage));

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

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

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

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

Subject: Edge Detection and Noise Filtering

From: fburton@nyx.net (Francis Burton)

Date: 18 Feb, 2011 14:27:17

Message: 32 of 34

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

Subject: Edge Detection and Noise Filtering

From: karoot RAZA

Date: 24 Feb, 2011 03:13:04

Message: 33 of 34

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);

Subject: plz help me regarding voice activity detection

From: karoot RAZA

Date: 24 Feb, 2011 05:44:04

Message: 34 of 34

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));

%常数设置
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);

%计算短时能量
amp=sum(abs(enframe(filter([1 -0.9375],1,x),framelen,framelnc)),2)

%调整能量门限
amp1=min(amp1,max(amp)/4);
amp2=min(amp2,max(amp)/8);

%开始端点检测
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, %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(1,1,1)
plot(x)

w=x(x1*framelnc:x2*framelnc,:);
figure(2)
plot(w)

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us