tags:

views:

333

answers:

4

I need to write a function to imread an image and convert it to grayscale. Is this correct:

function trial()

O = imread('m1.png');
G = rgb2gray(O);
imwrite(G,'s','jpg');

end

or is there a better way to write it?

A: 

As it is, your function is kind of useless, and could just be a script, since the function does not take any argument.

you don't need end at the end of your file - end is for ending loop, conditionals and the like.

David Cournapeau
Actually, with the use of nested functions, END can be needed in function definition. In this case, it is optional, but for some function structures, it is needed.
MatlabDoug
+2  A: 

That solution works, but you could make it more flexible by accepting arguments:

function trial(inputName, outputName)
    o = imread(inputName);
    g = rgb2gray(o);
    imwrite(g, outputName, 'jpg')

This way, you can batch up file runs.

Dan Lorenc
If you are going to process all the files in a directory, you should follow this video tutorial on the technique in MATLAB.http://blogs.mathworks.com/videos/2008/09/09/advanced-matlab-file-name-processing-from-directory-listing/
MatlabDoug
+5  A: 

You're on the right track, but I agree with Dan that you should add input arguments to make it more generally usable. Having to change the hardcoded file names every time you want to use it is not ideal.

If this function is designed for others to use, or even if it's just for yourself, I would suggest adding an H1 line, help text, and input type checking. For example:

function make_grayscale(inFile,outFile)
% MAKE_GRAYSCALE Converts an RGB image to grayscale
%    MAKE_GRAYSCALE(INFILE,OUTFILE) converts a truecolor RGB image stored in
% INFILE to a grayscale intensity image and writes it to OUTFILE.

  if ~ischar(inFile) || ~ischar(outFile),
    error('File name arguments must be character strings!');
  end

  ...(rest of function)...

end

Many people underestimate how useful these things are. When you set a function aside for a few months, it's easy to forget exactly how you wrote it to behave. The help reminds you (or others) how to use it, and the error checking helps give useful information when you have done something wrong. Also, having a descriptive H1 line gives you the option of using LOOKFOR to find functions that you may have forgotten the names of.

gnovice
+1  A: 

In addition you might want to let the function return something so you can use it later on.

function out = trial(imageName)

O = imread(imageName);
G = rgb2gray(O);
%imwrite(G,'s','jpg');
out = G;
end

Or whatever function you like. This way you don't need to call it from your disk next time you need the grayscale. You can use it much easier in a part of code calling the function.

x = trial('image.png')

Might be easier than writing to disc in most cases since I suppose you will use the grayscale image immediately after.

bastijn