Clear Filters
Clear Filters

How to get integer pixel coordinates from roi rectangle?

10 views (last 30 days)
I am having a trouble getting the pixel values from my roi rectangle. For example i have an 1200x1600 image, when i select the bottom right corner i get x2 y2 values as 1200.5 and 1600.5. Also other position values are floats such as 54.245. I want my xi yi positions as integer values because i am going to use these points later for image processing. I tried using round() function but it didnt work.
My code is:
ax=gca;
roi= drawrectangle(ax);
position =roi.Position;
x1 = position(1);
x2 = x1 + position(3);
y1 = position(2);
y2 = y1 + position(4);

Accepted Answer

Turlough Hughes
Turlough Hughes on 4 Jan 2022
Edited: Turlough Hughes on 4 Jan 2022
When used on images, the drawrectangle function uses intrinsic image coordinates (see this documentation) as shown by the x and y axes here:
For intrinsic coordinates, the integer x and y positions correspond to the pixel centers, that is (colNum, rowNum) are the intrinsic x and y coordinate. Hence, for the pixel indices and intrinsic coordinates to align, the top left corner of an image is located at (0.5,0.5). This can be awkward to wrap your head around at first but once you realise it's just (colNum, rowNum) it makes a lot of sense. It follows that the center of the bottom right pixel is actually at the position (1200,1600), and the position (1200.5, 1600.5) is the bottom right corner of the bottom right pixel in your image.
Ultimately, rounding the values x1, y1, x2, y2, DOES give you values rounded to the nearest pixel indices, but I can think of one edge case which is the example you provided; that (1200.5, 1600.5) would round to (1201,1601). So perhaps the approach to take there is to use a conditional if/else block just for that scenario.
  3 Comments
Turlough Hughes
Turlough Hughes on 4 Jan 2022
Sometimes it's helpful as well to view the axes:
% For example:
I = imread('cameraman.tif');
imshow(I);
axis on
guanin hae
guanin hae on 4 Jan 2022
I used round and if/else statements like you suggested and it worked, thank you!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!