Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 416
dsg Avatar asked Jun 28 '12 02:06

dsg


People also ask

How do you get pixel coordinates in Matlab?

You can also obtain pixel value information from a figure with imshow by using the impixelinfo function. To save the pixel location and value information displayed, right-click a pixel in the image and choose the Copy pixel info option. Image Viewer copies the x- and y-coordinates and the pixel value to the clipboard.


1 Answers

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)

like image 133
Amro Avatar answered Oct 04 '22 14:10

Amro