MATLAB How to convert axis coordinates to pixel coordinates?

13,274

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)

Share:
13,274
dsg
Author by

dsg

Updated on June 25, 2022

Comments

  • dsg
    dsg almost 2 years

    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.