6

What is the preferred way of converting from axis coordinates (e.g. those taken in by plot or those output in point1 and point2 of houghlines) to pixel coordinates in an image?

I see the function axes2pix in the Mathworks documentation, but it is unclear how it works. Specifically, what is the third argument? The examples just pass in 30, but it is unclear where this value comes from. The explanations depend on a knowledge of several other functions, which I don't know.

The related question: Axis coordinates to pixel coordinates? suggests using poly2mask, which would work for a polygon, but how do I do the same thing for a single point, or a list of points?

That question also links to Scripts to Convert Image to and from Graph Coordinates, but that code threw an exception:

Error using  / 
Matrix dimensions must agree.
4

2 回答 2

2

考虑以下代码。它显示了如何从轴坐标转换为图像像素坐标。

如果您使用自定义 XData/YData 位置而不是默认1:width1:height. 在下面的示例中,我在 x/y 方向上移动了 100 和 200 像素。

function imageExample()
    %# RGB image
    img = imread('peppers.png');
    sz = size(img);

    %# show image
    hFig = figure();
    hAx = axes();
    image([1 sz(2)]+100, [1 sz(1)]+200, img)    %# shifted XData/YData

    %# hook-up mouse button-down event
    set(hFig, 'WindowButtonDownFcn',@mouseDown)

    function mouseDown(o,e)
        %# get current point
        p = get(hAx,'CurrentPoint');
        p = p(1,1:2);

        %# convert axes coordinates to image pixel coordinates
        %# I am also rounding to integers
        x = round( axes2pix(sz(2), [1 sz(2)], p(1)) );
        y = round( axes2pix(sz(1), [1 sz(1)], p(2)) );

        %# show (x,y) pixel in title
        title( sprintf('image pixel = (%d,%d)',x,y) )
    end
end

截屏

(注意轴限制不是从 开始的(1,1),因此需要axes2pix

于 2012-06-29T16:41:35.890 回答
0

可能有一种我没有听说过的内置方式,但这应该不难从头开始......

set(axes_handle,'units','pixels');
pos = get(axes_handle,'position');
xlim = get(axes_handle,'xlim');
ylim = get(axes_handle,'ylim');

使用这些值,您可以轻松地将坐标轴坐标转换为像素。

x_in_pixels = pos(1) + pos(3) * (x_in_axes-xlim(1))/(xlim(2)-xlim(1));
%# etc...

以上pos(1)用作图中轴的 x 偏移量。如果您不关心这一点,请不要使用它。同样,如果您希望它在屏幕坐标中,请添加通过以下方式获得的位置的 x 偏移量get(figure_handle,'position')

于 2012-06-28T02:51:52.933 回答