# How to convert from cartesian coordinates to pixel indices on a 2D image

40 views (last 30 days)
Maura Monville on 4 Apr 2016
Commented: win hlaing on 14 Sep 2018
Please take a look at the attached MatLab script. The goal is to plot the image intensity across a diameter passing through the image center and making an arbitrary angle 'phi' with the Cartesian x_axis. No averaging over image intensities. I can calculate the pixel indices of one end of the diameter as follows:
[rows columns] = size(img);
xmid = ceil(rows/2);
ymid = ceil(columns/2);
phi = 30*pi/180;
xs = xmid + round(ceil(radius * cos(phi)))
ys = ymid + round(ceil(radius * sin(phi)))
However, I am unable to get the indices of the other diameter end. Geometrically I would do:
xf = xmid + round(ceil(radius * cos(phi + pi)))
yf = ymid + round(ceil(radius * sin(phi + pi)))
The last two formulae do not generate the righ pixel indices of the other diameter end.
I tried the method indicated in an on-line example using function 'axes2pix' but MatLab issued an error upon getting XData and YData ... God knows why ...
I would greatly appreciate some help at computing correctly the pixel indices of a diameter passing through the 2D image center at an arbitrary angle 'phi'.
Maura
win hlaing on 14 Sep 2018
xf = xmid + round(ceil(radius * cos(phi + pi))) yf = ymid - round(ceil(radius * sin(phi + pi)))
you just have to change + sign for y axis.. coz on paper cartesian plane for x and y and computer base pixel plane are not the same. For computer, y axis is changing. That why you have to subtract your r*sin theta from your ymid.

Walter Roberson on 4 Apr 2016
You have
[rows columns] = size(img);
Is your image RGB? If so then that line is wrong and you need
[rows, columns, ~] = size(img);
Maura Monville on 5 Apr 2016
Very good explanation illustrated by simple examples. Thank you so much for clarifying my doubts.

Kuifeng on 4 Apr 2016
%I would suggest use the 'ceil' and 'floor' combination for pixels
xs = xmid + round(ceil(radius * cos(phi)));
ys = ymid + round(floor(radius * sin(phi)));
xf = xmid + round(floor(radius * cos(phi + pi)));
yf = ymid + round(ceil(radius * sin(phi + pi)));
##### 2 CommentsShowHide 1 older comment
Kuifeng on 5 Apr 2016
%for example,
xmid = 300;
ymid = 300;
phi = 30*pi/180;
xs = xmid + round(ceil(radius * cos(phi)));
ys = ymid + round(floor(radius * sin(phi)));
xf = xmid + round(floor(radius * cos(phi + pi)));
yf = ymid + round(ceil(radius * sin(phi + pi)));
hold on,
plot([xs xf], [ys yf], 'r*-');
axis equal 