用Matlab的直接获取新矩形的坐标

时间:2013-11-19 19:18:20

标签: matlab image-processing

对于我的项目,我需要很多图片来提取投资回报率。当我的项目开始时,我希望显示一张图片,然后用户选择他/她想要的ROI。函数imrect似乎正在这样做。一旦拖动或调整大小,我试图获取矩形的坐标。问题是返回的值似乎不正确。

我似乎无法找到问题并且相关问题没有帮助。我尝试使用imcrop,但无法做得更好......

function [ new_image ] = getRoi(image)

rect = size(image);
rect = round(rect ./2);

figure, imshow(image);

h = imrect(gca, [5 5 rect(2) rect(1)]);

addNewPositionCallback(h,@(p) title(mat2str(p,3)));
fcn = makeConstrainToRectFcn('imrect',get(gca,'XLim'),get(gca,'YLim'));
accepted_pos = wait(h);
setPositionConstraintFcn(h,fcn);
%getPositionConstraintFcn(h);

pos = getPosition(h);

if round(pos(1)) < round(pos(2))
    X1 = round(pos(1))
    X2 = round(pos(2))
else
    X1 = round(pos(2))
    X2 = round(pos(1))
end

if round(pos(3)) < round(pos(4))
    Y1 = round(pos(3))
    Y2 = round(pos(4))
else
    Y1 = round(pos(4))
    Y2 = round(pos(3))
end

new_image = image(Y1:Y2, X1:X2);

%name = strcat('Roi_', datestr(clock, 'yyyymmddTHHMMSS'),'.png');
%prtIm(new_image, name, '-s');
new_image = image;

end

1 个答案:

答案 0 :(得分:3)

getPosition返回[xmin, ymin, width, height]。要获得所需的坐标,请尝试

X1 = round(pos(1));
Y1 = round(pos(2));
X2 = round(X1 + pos(3));
Y2 = round(Y1 + pos(4));