Matlab:将全局坐标转换为图形坐标

ola*_*ndo 4 matlab coordinates

如果我得到坐标

coords = get(0,'PointerLocation');
Run Code Online (Sandbox Code Playgroud)

如何将它们转换为通过点获得的积分ginput

即,我想从中得到相同的值

coords = get(0,'PointerLocation');
coords=someConversion(coords);
Run Code Online (Sandbox Code Playgroud)

正如我本来打电话的那样

coords=ginput(1);
Run Code Online (Sandbox Code Playgroud)

然后在与前一位代码相同的位置点击图中的鼠标.

gno*_*ice 8

以下是如何进行此转换的示例...

假设你有一个数字,那个数字包含一个带句柄的轴对象hAxes.使用该功能ginput可以选择轴内的点.要获得等效的点集get(0, 'PointerLocation'),其中给出了与屏幕相关的坐标,您必须考虑图形位置,轴位置,轴宽度/高度和轴限制.

这样做很棘手,因为您希望以相同的单位进行位置测量.如果你想以像素为单位计算所有东西,这意味着你必须设置'Units'对象的属性'pixels',获取位置,然后将'Units'属性设置回原来的状态.我通常做自己的功能get_in_units来做这个部分:

function value = get_in_units(hObject, propName, unitType)

  oldUnits = get(hObject, 'Units');  % Get the current units for hObject
  set(hObject, 'Units', unitType);   % Set the units to unitType
  value = get(hObject, propName);    % Get the propName property of hObject
  set(hObject, 'Units', oldUnits);   % Restore the previous units

end
Run Code Online (Sandbox Code Playgroud)

使用上面的函数,您可以创建另一个get_coords获取屏幕坐标的函数并将它们转换为轴坐标:

function coords = get_coords(hAxes)

  % Get the screen coordinates:
  coords = get_in_units(0, 'PointerLocation', 'pixels');

  % Get the figure position, axes position, and axes limits:
  hFigure = get(hAxes, 'Parent');
  figurePos = get_in_units(hFigure, 'Position', 'pixels');
  axesPos = get_in_units(hAxes, 'Position', 'pixels');
  axesLimits = [get(hAxes, 'XLim').' get(hAxes, 'YLim').'];

  % Compute an offset and scaling for coords:
  offset = figurePos(1:2)+axesPos(1:2);
  axesScale = diff(axesLimits)./axesPos(3:4);

  % Apply the offsets and scaling:
  coords = (coords-offset).*axesScale+axesLimits(1, :);

end
Run Code Online (Sandbox Code Playgroud)

结果coords应该与您使用的结果接近ginput.请注意,如果轴对象嵌套在图中的任何uipanel对象中,则还必须考虑面板位置.


例:

为了说明上面代码的行为,这里有一个简洁的小例子.创建上述函数后,创建第三个函数:

function axes_coord_motion_fcn(src, event, hAxes)

  coords = get_coords(hAxes);               % Get the axes coordinates
  plot(hAxes, coords(1), coords(2), 'r*');  % Plot a red asterisk

end
Run Code Online (Sandbox Code Playgroud)

然后运行以下代码:

hFigure = figure;  % Create a figure window
hAxes = axes;      % Create an axes in that figure
axis([0 1 0 1]);   % Fix the axes limits to span from 0 to 1 for x and y
hold on;           % Add new plots to the existing axes
set(hFigure, 'WindowButtonMotionFcn', ...  % Set the WindowButtonMotionFcn so
    {@axes_coord_motion_fcn, hAxes});      %   that the given function is called
                                           %   for every mouse movement
Run Code Online (Sandbox Code Playgroud)

当您将鼠标指针移动到图形轴上时,您应该会在其后面看到一条红色星号,如下所示:

在此输入图像描述