use imcrop and specify width and height but not starting location?

10 views (last 30 days)
Is there a way to create a specified size rectangle on an image without a set starting point? So I could move the ROI around on the image and save that chunk but without being able to click an drage to change the size of the rectangle?

Accepted Answer

DGM on 5 Oct 2022
Edited: DGM on 5 Oct 2022
This is an attempt to constrain the size of the ROI object during user interaction.
% say you have an image
inpict = imread('peppers.png');
% and you know the box geometry
cropsz = [200 100]; % [x y] (pixels)
% start by displaying the image
% create an ROI object with the specified size
% at some default location (e.g. the image origin)
myROI = drawrectangle(gca,'position',[0 0 cropsz]);
addlistener(myROI,'MovingROI',@(a,b) forcesize(myROI,cropsz));
% the ROI object can be manually dragged around the image
% attempts to resize the object will be prevented
% a simple means to wait for the user
input('Press enter when you''re done moving the ROI object.','s');
% crop using the offsets from the ROI and the specified size
outpict = imcrop(inpict,[myROI.Position(1:2) cropsz]);
% show the result
function forcesize(hObject,fixedsz)
hObject.Position(3:4) = fixedsz;

More Answers (1)

Image Analyst
Image Analyst on 4 Oct 2022
Maybe try drawrectangle. Demo attached. Adapt as needed.

Community Treasure Hunt

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

Start Hunting!