Marta Sampietro
Marta Sampietro

Reputation: 339

Obtain pixel position from an image by mouse click in MATLAB

I am developing a program in MATLAB that will show an image of a scene and the user will click on any point on the image and the program will eliminate all the pixels of the image that have the color of the pixel that the user selected.

I have done everything I need or it to work, but I only have one problem: when I use the ginput function in order for the user to click on any point he likes, the function allows to click anywhere on the figure, including outside the image, thus making it hard to get the right coordinates he clicks on. This is what I have at the moment:

figure;
imshow(img)
[x,y] = ginput(1);
close all
v = img(int8(x),int8(y));

% Put all the pixels with the same value as 'v' to black
...
%

Is there any other way that can restrict the clickable area to the area of the image alone?

Upvotes: 1

Views: 927

Answers (1)

Suever
Suever

Reputation: 65430

You can't restrict ginput to an axes object. Probably a better way to accomplish this would be to use the ButtonDownFcn of the image.

hfig = figure;
him = imshow(img);

% Pause the program until the user selects a point (i.e. the UserData is updated)
waitfor(hfig, 'UserData')

function clickImage(src)
    % Get the coordinates of the clicked point
    hax = ancestor(src, 'axes');
    point = get(hax, 'CurrentPoint');
    point = round(point(1,1:2));

    % Make it so we can't click on the image multiple times
    set(src, 'ButtonDownFcn', '')

    % Store the point in the UserData which will cause the outer function to resume
    set(hfig, 'UserData', point);
end

% Retrieve the point from the UserData property
xy = get(hfig, 'UserData');

Upvotes: 1

Related Questions