注释 - 使用 imrect 强制正方形

Annotation - Enforce a square using imrect

我有一个 Matlab 程序要求用户围绕场景中的人画一个矩形(我后来使用 imcrop 提取该区域)。我需要强制用户画一个正方形。我正在使用 imrect 函数,但我无法强制生成正方形,也找不到有关如何执行此操作的文档。

似乎 imrect can take a position-constraining function 作为输入参数。此函数指定如下:

Whenever the object is moved because of a mouse drag, the constraint function is called using the syntax:

constrained_position = fcn(new_position)

位置是 [xleft ybottom width height].

形式的向量

所以试试这个:

axis equal %// same sccale on both axes
axis manual %// freeze axes size 
h = imrect('PositionConstraintFcn', @(x) [x(1) x(2) min(x(3),x(4))*[1 1]])

最简单的方法是在创建矩形期间将 setFixedAspectRatioMode 方法设置为 true,首先绘制一个正方形。 (检查 here)。

示例:

%// Make sure it's initially a square!!
hRect = imrect(gca, [10 10 100 100]);

setFixedAspectRatioMode(hRect,1)

那么无论你如何改变位置,它都将保持正方形。但是请注意,与 Luis 的解决方案相反,用户无法指定正方形的初始位置。