dsg
dsg

Reputation: 13004

MATLAB How to convert axis coordinates to pixel coordinates?

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.

Upvotes: 6

Views: 13848

Answers (2)

Amro
Amro

Reputation: 124563

Consider the following code. It shows how to convert from axes coordinates to image pixel coordinates.

This is especially useful if you plot the image using custom XData/YData locations other than the default 1:width and 1:height. I am shifting by 100 and 200 pixels in the x/y directions in the example below.

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

screenshot

(note how the axis limits do not start at (1,1), thus the need for axes2pix)

Upvotes: 2

tmpearce
tmpearce

Reputation: 12693

There may be a built-in way that I haven't heard of, but this shouldn't be hard to do from scratch...

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

Using these values, you can convert from axes coordinates to pixels easily.

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

The above uses pos(1) as the x-offset of the axes within the figure. If you don't care about this, don't use it. Likewise, if you want it in screen coordinates, add the x-offset of the position obtained by get(figure_handle,'position')

Upvotes: 0

Related Questions