Search code examples
arraysmatlabmatrixcoordinatedisp

MATLAB Add Mouse Click Coordinate to Matrix?


I am creating an image processing project in matlab. I want to get 5 coordinates from image with mouse and save them to a matrix. When I run project, I click only once but the matrix is taking same coordinates. How can I fix it ?

function ImageClickCallback ( objectHandle , eventData )
array = 3:2;
for i = 1:3
   axesHandle  = get(objectHandle,'Parent');
   coordinates = get(axesHandle,'CurrentPoint'); 
   coordinates = coordinates(1,1:2);
   array(i,1) = coordinates(1);
   array(i,2) = coordinates(2);
end
disp(array);

For example when I click a point on image, I am taking this result. I can't select another points.

99.3806   37.1915 
99.3806   37.1915
99.3806   37.1915

Solution

  • A much safer alternative would be to use ginput, with which you can select a variable number of points and store their coordinates easily. You don't need a loop; the coordinates are stored once all the points are selected.

    Here is a simple example:

    clear
    clc
    close all
    
    A = imread('peppers.png');
    
    imshow(A,[]);
    hold on
    
    %// Number of points
    N = 5;
    
    array = zeros(N,2);
    
    %// Use a for loop and plot 1 point at a time.
    for k = 1:N
    
       [array(k,1),array(k,2)] = ginput(1);
    
       %// Display the points
       scatter(array(k,1),array(k,2),60,'k','filled')
    
    end
    

    Sample output for array:

       123.0000   87.0000
       95.0000  206.0000
      256.0000   85.0000
      236.0000  253.0000
      395.0000  117.0000
    

    And the image with the points displayed:

    enter image description here

    Therefore, you could would look like this:

    function ImageClickCallback ( objectHandle , eventData )
    
       array = zeros(3,2);
    
       [array(:,1),array(:,2)] = ginput(3);