Question

With the following code, I can easily draw one draggable rectangle on given image.

figure; 
imshow('image.png');

h = imrect;
p = wait(h);                                              % get the rect position
rectangle('Position', p, 'LineWidth',2, 'EdgeColor','r'); % draw here

enter image description here

The problem is: how can I draw multiple draggable rectangles on the image? And in addition, the number of the rectangles are not known pre-hand.

P.S. It will become easier if I already the number of rectangles to draw. For example, if I want to draw 2 rectangels, the following code will work, i.e. just put as many of wait():

figure; 
imshow('image.png');

h = imrect;
p = wait(h);                                              % get the rect position
rectangle('Position', p, 'LineWidth',2, 'EdgeColor','r'); % draw here
p2 = wait(h);                                             % get the rect position
rectangle('Position', p2, 'LineWidth',2, 'EdgeColor','r'); % draw here
Was it helpful?

Solution

One way is to wrap the position acquisition in a while loop and add some sort of uicontrol to indicate when you're done. In this case, it's just a pushbutton that deletes the imrect handle when you're done. If the handle is deleted, h is no longer valid, so isvalid stops the while loop. ~isempty is used as the last returned value of p will be empty.

Note that this code overwrites p each time so if you want to record all the positions, not just draw rectangles, you will need to add that in.

figure
imshow(I)
h = imrect

uicontrol('Style', 'pushbutton', 'String', 'Done',...
        'Position', [20 20 50 20],...
        'Callback', 'delete(h)');

while isvalid(h)
  p = wait(h);          
  if ~isempty(p)                                    
      rectangle('Position', p, 'LineWidth',2, 'EdgeColor','r');
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top