简体   繁体   中英

User defined functions in MATLAB

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?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM