function measure_mm2pix
%The script will display all images in a selected folder,
%then prompts the user to click on two points (on the tape) which are 100mm
%away from each other.  Once the user clicks on the photo there will be a
%short pause before the measuring tool becomes active.  Once the user is
%done clicking on the two points, the ENTER button must be pushed to
%continue.
%
% Written by Daniel Buscombe, various times in 2012 and 2013
% while at
% School of Marine Science and Engineering, University of Plymouth, UK
% then
% Grand Canyon Monitoring and Research Center, U.G. Geological Survey, Flagstaff, AZ 
% please contact:
% dbuscombe@usgs.gov
% for lastest code version please visit:
% https://github.com/dbuscombe-usgs
% see also (project blog):
% http://dbuscombe-usgs.github.com/
%====================================
%   This function is part of 'dgs-gui' software
%   This software is in the public domain because it contains materials that originally came 
%   from the United States Geological Survey, an agency of the United States Department of Interior. 
%   For more information, see the official USGS copyright policy at 
%   http://www.usgs.gov/visual-id/credit_usgs.html#copyright
%====================================

%Use the following var to set the amount of time (seconds) between first clicking on
%the photo and the pixel measuring tool becoming active

% %Get folder where photos to be measured reside.
% phtdir = uigetdir();
% 
% %Get folder where output file will go.
% [outfilename, outpathname] = uiputfile( ...
%     {'*.txt', 'text files'}, ...
%     'Save mm_pix.txt',[phtdir filesep 'mm_pix.txt']); % 'filesep' added DB jul09


outname=[pwd filesep 'mm_pix.txt'];


[image_name, image_path] = uigetfile({'*.tiff';'*.TIF';'*.TIFF';'*.tif';...
    '*.JPG';'*.jpg';'*.BMP';'*.bmp';'*.PNG';'*.png'},...
    'Load scale image ...', 'MultiSelect', 'on');

if isequal(image_name,0) || isequal(image_path,0)
    disp('You pressed cancel') % msg if cancel button pressed
    
else % cancel button not pressed

[mmperpix]=func_mm2pix(image_path,image_name);

fid=fopen(outname,'w');
fprintf(fid,'%f\n',mmperpix);
fclose(fid);

close
disp('------------------------------------------------------------------');
disp(num2str(mmperpix'));
disp('------------------------------------------------------------------');
disp(['File written to: ' outname]); 

end


function [mmperpix]=func_mm2pix(image_path,image_name)

pausetime=1.5;

if iscell(image_name) % list of files

    for i = 1:length(image_name)
    rgb=imread([image_path(1,:),char(image_name(i))]); 
    
        %turn off warnings
    warning off all
    
    clf
    himg=imagesc(rgb); 
    %turn on warnings
    warning on all
    zoom on
    disp('------------------------------------------------------------------');
    disp(['Displaying image: ' char(image_name(i))]);
    disp('Zoom in to measuring tape...');
    %zoom
    k=waitforbuttonpress;
    
    point1 = get(gca,'CurrentPoint');    % button down detected
finalRect = rbbox;                   % return figure units
point2 = get(gca,'CurrentPoint');    % button up detected
point1 = point1(1,1:2);              % extract x and y
point2 = point2(1,1:2);
p1 = min(point1,point2);             % calculate locations
offset = abs(point1-point2);         % and dimensions
x = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)];
y = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)];
    axis([min(x) max(x) min(y) max(y)])
    
    pause(pausetime);
   
    % prompts the user for the distance to divide by (defaults to 100mm)
   prompt={'What is the distance, in mm, you will measure?'};
   name='';
   numlines=1;
   defaultanswer={'100'};
    
   answer=inputdlg(prompt,name,numlines,defaultanswer); answer=char(answer);
   mm=str2num(answer);
    
    disp(['Click on two points, ',num2str(mm),' mm apart, then hit ENTER on the keyboard']);
    
    % allows for mistakes in ruler measuring
    [answer,x1,x2,y1,y2]=cycle;
                
    if numel(answer)==3
        disp('Calculating ....');
        [pixlength]=dist(x1,y1,x2,y2);
        mmperpix(i)=mm/pixlength;
    else
        while numel(answer)~=3
           [answer,x1,x2,y1,y2]=cycle;
        end
        [pixlength]=dist(x1,y1,x2,y2);
        mmperpix(i)=mm/pixlength;
    end
    
    end
    %=====================
    
    else % just 1 photo
    
    rgb=imread([image_path,image_name]); 
    
        %turn off warnings
    warning off all
    
    clf
    himg=imagesc(rgb); 
    %turn on warnings
    warning on all
    zoom on
    disp('------------------------------------------------------------------');
    disp(['Displaying image: ' image_name]);
    disp('Zoom in to measuring tape...');
    %zoom
    k=waitforbuttonpress;
    
    point1 = get(gca,'CurrentPoint');    % button down detected
finalRect = rbbox;                   % return figure units
point2 = get(gca,'CurrentPoint');    % button up detected
point1 = point1(1,1:2);              % extract x and y
point2 = point2(1,1:2);
p1 = min(point1,point2);             % calculate locations
offset = abs(point1-point2);         % and dimensions
x = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)];
y = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)];
    axis([min(x) max(x) min(y) max(y)])
    
    pause(pausetime);
   
    % prompts the user for the distance to divide by (defaults to 100mm)
   prompt={'What is the distance, in mm, you will measure?'};
   name='';
   numlines=1;
   defaultanswer={'100'};
    
   answer=inputdlg(prompt,name,numlines,defaultanswer); answer=char(answer);
   mm=str2num(answer);
    
    disp(['Click on two points, ',num2str(mm),' mm apart, then hit ENTER on the keyboard']);
    
    % allows for mistakes in ruler measuring
    [answer,x1,x2,y1,y2]=cycle;
                
    if numel(answer)==3
        disp('Calculating ....');
        [pixlength]=dist(x1,y1,x2,y2);
        mmperpix=mm/pixlength;
    else
        while numel(answer)~=3
           [answer,x1,x2,y1,y2]=cycle;
        end
        [pixlength]=dist(x1,y1,x2,y2);
        mmperpix=mm/pixlength;
    end

    
end



%--------------------------------------------------------------------------
function [d]=dist(x1,y1,x2,y2)
%DISTANCE calculates the distance between two coordinate pairs
%   USAGE:[distance]=distance(x1,y1,x2,y2)
%
d=sqrt(((x2-x1).*(x2-x1))+((y2-y1).*(y2-y1)));

%--------------------------------------------------------------------------


function [answer,x1,x2,y1,y2]=cycle

d=ginput(2); d=d(:);
x1=d(1); x2=d(2); y1=d(3); y2=d(4);
 
hold on, h=line([x1 x2],[y1 y2]); 
set(h,'Color','r','LineWidth',3)
    
answer = questdlg('Are you happy with this selection?', ...
                    'Question', 'Yes');




