% Authors: Steven Su and Robert Kim
% Date: May 17, 2011
% Interventional Photoacoustic Registration
% 600.446: CIS II, Spring 2011
% The Johns Hopkins University

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Computes centroid coordinates of Stereocamera laser spot after
% thresholding image and letting user click on the laser spot. User needs
% to click on laser spot on Figure 2.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [cx,cy] = getCameraPoint(image_name)

% Imports image file and converts it to grayscale image
Laser_Color=imread(image_name);
I=rgb2gray(Laser_Color);

% Counter to determine which threshold condition was used.
counter=0;

% Thresholds image based on the type of image. Converts the thresholded
% image to black and white.
if(strfind(image_name,'low_right_corner'))
    BW_Laser=im2bw(Laser_Color,.3);
    counter=1;
end
if(strfind(image_name,'left_upper_cornerL'))
    BW_Laser=im2bw(Laser_Color,.7);
    counter=1;
end
if counter==0
    threshold=graythresh(I);
    BW_Laser=im2bw(I,threshold);
end

% Displays thresholded image
figure(1);
imshow(BW_Laser);

% Thresholds image and removes any regions with less than 100 pixels. Then
% asks user to select region that corresponds to laser spot.
BW_Laser2=bwareaopen(BW_Laser,100,8);
figure(2);
BW_Laser_Select=bwselect(BW_Laser2);
close(1);

% Shows the user selected region
figure(3);
imshow(BW_Laser_Select)

% Labels the region of the thresholded image so that properties of the user
% selected region can be obtained.
[L,num]=bwlabeln(BW_Laser_Select,8);

% Computes the weighted centroid of the selected region/laser spot.
Coord_Struct=regionprops(L,BW_Laser_Select,'WeightedCentroid');

% Stores the x,y coordinates of the weighted centroid.
v=cat(1,Coord_Struct.WeightedCentroid);
cx=v(:,1);
cy=v(:,2);

% Displays the centroid over the original image
figure(4);
image(Laser_Color)
axis image;
hold on;
plot(cx,cy,'rh');
pause(2);
close(3);
