フィルターのクリア

How to convert script into a function

1 回表示 (過去 30 日間)
Ömer Yaman
Ömer Yaman 2020 年 9 月 28 日
コメント済み: Ameer Hamza 2020 年 9 月 28 日
Hello all,
I am quite beginner for matlab coding. I have a code which selects a ROI over an image. You may find code below.
clear all
clc
randomimage=randi([0 2^16-1], 256, 256, 'uint16');
%imshow(randomimage)
S = [64 64 127 127];
figure, imshow(randomimage);
h = imrect(gca, S);
addNewPositionCallback(h,@(p) title(mat2str(p,3)));
fcn = makeConstrainToRectFcn('imrect',get(gca,'XLim'),get(gca,'YLim'));
setPositionConstraintFcn(h,fcn)
position = wait(h);
ROIIMAGE = imcrop(randomimage,position);
close all
figure, imshow(ROIIMAGE);
Code generates a random 16 bit image and create a size adjustable rectangular to select ROI. Then selected ROI will be opened as another figure by double clicking the rectangle.
My question is how can I put this code into a function. Thanks in advance.

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 9 月 28 日
Defining a function needs you to specify what are inputs and outputs. There are several ways you can write this as a function. Read here: https://www.mathworks.com/help/matlab/ref/function.html.
For example,
function fig = myFunction(randomimage)
%imshow(randomimage)
S = [64 64 127 127];
figure, imshow(randomimage);
h = imrect(gca, S);
addNewPositionCallback(h,@(p) title(mat2str(p,3)));
fcn = makeConstrainToRectFcn('imrect',get(gca,'XLim'),get(gca,'YLim'));
setPositionConstraintFcn(h,fcn)
position = wait(h);
ROIIMAGE = imcrop(randomimage,position);
close all
fig = figure;
imshow(ROIIMAGE);
end
This function takes randomImage as input and returns the figure handle of the last figure as output. You can call it like this
randomimage=randi([0 2^16-1], 256, 256, 'uint16');
myFunction(randomimage);
or following if you need the figure handle too
randomimage=randi([0 2^16-1], 256, 256, 'uint16');
f = myFunction(randomimage);
  2 件のコメント
Ömer Yaman
Ömer Yaman 2020 年 9 月 28 日
Thank you!
Ameer Hamza
Ameer Hamza 2020 年 9 月 28 日
I am glad to be of help!

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by