MATLAB: Event listener for multiple draggable rectangles using imrect in matlab

imrect

function computeButton_Callback(hObject, eventdata, handles)
% hObject handle to computeButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
PImage=handles.ProcessedImage;
Image=handles.Image;
imshow(Image);
hold on;
bw=bwconncomp(PImage,4);
regions=regionprops(bw,'BoundingBox','PixelIdxList');
for i=1:length(regions)
box=regions(i).BoundingBox;
h=imrect(gca,box);
%rectangle('Position',box,'EdgeColor','black','LineWidth',2);
end
%I want to make an event listener that would record the
%properties(height,width) of all the rectangles and even
%the changes on each of the draggable rectangles on the Image.

Best Answer

Do you really want to listen to all the changes in position of the rectangles? There will be a lot of event recorded when the user drag a handle. If you only need to know what the current position of the rectangles is at some point in the code, you can just query it. For that, you obviously need to save the rectangle handles somewhere:
%...
hrectangles = gobjects(numel(regions), 1); %allocate storage for rectangle handles
for i = 1:numel(regions)
box = regions(i).BoundingBox;
hrectangles(i) = imrect(gca, box); %store rectangle handles
end
%...
%code where you need to know what the coordinates of the rectangles are:
rectpos = cell2mat(arrayfun(@getPosition, hrectangles, 'UniformOutput', false));
If you really want to listen to all the changes, you can add a new position callback to each rectangle and do whatever you need to do in that callback:
for i = 1:numel(regions)
box = regions(i).BoundingBox;
h = imrect(gca, box);
h.addNewPositionCallback(@(newpos) RectPositionChangedCallback(h, newpos)
end
with
function RectPositionChangedCallback(recthandle, newposition)
%do something with new position
end