crop image with fixed x/y ratio

2019-07-12 03:13发布

问题:

I want to crop image using following code. but i want to user only can select the crop area with a predefined x/y ratio.for example if x=2,y=2 ,then user can only use mouse to select an area with (x/y)=1 ratio.

I = imread('image.jpg');
[rows columns numberOfColorBands] = size(I);
I2 = imcrop(I);
imshow(I), figure, imshow(I2)

回答1:

You could use imrect to produce the coordinates, and then pass those into imcrop.

figure, imshow(I);
h = imrect(gca,[10 10 100 100]); 
setFixedAspectRatio(h,1); % this fixes the aspect ratio; user can now change size/position
position = wait(h); % returns coordinates in "position" when user doubleclicks on rectangle
I2 = imcrop(I,position);
figure, imshow(I2);

In the actual code, you'll have to replace [10 10 100 100] with something of the appropriate size/aspect ratio for your images. You may want to add other constraints to imrect (for example to stop the user moving the rectangle outside the actual image).