Sunday, July 07, 2013

Matlab: Click mouse points on an image

classdef GuiImagePointClicker < handle
%GuiImagePointClicker Point selection on an image with the ability
% to delete points using backspace.
%
%
% EXAMPLE
% I = load('gatlin');
% mygui = GuiImagePointClicker(I.X./max(I.X(:)));
% mygui.x
% mygui.y
%
properties(SetAccess = private)
x = [];
y = [];
I = [];
imh = 0;
fh = 0;
ptHandles = [];
end
methods
function obj = GuiImagePointClicker(I)
obj.init();
obj.I = I;
obj.getPoints();
end
function init(obj)
obj.I = [];
obj.x = [];
obj.y = [];
obj.imh = 0;
obj.fh = 0;
obj.ptHandles = [];
end
function getPoints(obj)
% show image
obj.fh = figure();
obj.imh = imshow(obj.I);
hold on;
fprintf(1, ['\n\nPress mouse to put points.\n', ...
'Enter on the figure to finish and backspace to ', ...
'remove last point.\n\n']);
% set callback function for keyboard press
set(obj.fh, 'KeyPressFcn', ...
@(s,e) obj.callback_keyPressFcn(s,e) );
% set callback function for mouse press
set(obj.imh, 'ButtonDownFcn', ...
@(s,e) obj.callback_mousePressFcn(s,e) );
end
function callback_mousePressFcn(obj, hObject, ~)
% get position of mouse click
imaxis = get(hObject,'parent');
point = get(imaxis,'currentpoint');
x = point(1,1);
y = point(1,2);
% save it
obj.x(end + 1) = x;
obj.y(end + 1) = y;
% show the click points
obj.showPoints();
end
function callback_keyPressFcn(obj, hObject, evnt)
pressedKey = evnt.Key;
switch pressedKey
case 'backspace'
obj.deleteOnePoint();
case 'return'
obj.closeFigure();
end
end
function deleteOnePoint(obj)
numPoints = numel(obj.x);
if numPoints < 1
disp('No points to delete');
return;
end
% remove last point
obj.x(end) = [];
obj.y(end) = [];
% redraw points
obj.showPoints();
end
function closeFigure(obj)
disp('finished.');
close(obj.fh);
end
function showPoints(obj)
%first delete all points and than redraw them
arrayfun(@delete, obj.ptHandles);
obj.ptHandles = [];
% redraw points
for pi = 1:numel(obj.x)
x = obj.x(pi);
y = obj.y(pi);
ph = plot(x, y, 'or', ...
'MarkerFaceColor', 'red', ...
'MarkerSize', 6);
obj.ptHandles(end+1) = ph;
end
end
end
end