%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This script reads picture and exif data from multiple jpg images and 
% plots an exposure diagramm.
% 
% Copyright (c) 2008 - by Lukasz Panek
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all;
close all;

startpic = 8576;
stoppic  = 8776;

directory = 'exposuretest'; % image directory

pos = 0;

if fopen('exposuredata.mat')>0
    loadpics = false; % recall saved data from 'exposuredata.mat' if existent
    fclose('all'); % close file (all files)
else
    loadpics = true; % load images
end


if(loadpics) % load pics

    for i = startpic:stoppic
        % generate file name
        fname = sprintf('%s/img_%4d.jpg',directory,i)

        [fid, message] = fopen(fname,'r');

        if fid>0 % if file existent
            fclose(fid);

            pos = pos + 1;

            % read exif data
            picexif = exifread(fname);

            % read picture data
            dpic = imread(fname);
            ij = size(dpic);
            % save number
            number(pos) = i;
            % save time and aperture
            ExposureTime(pos) = picexif.ExposureTime;
            FNumber(pos) = picexif.FNumber;
            % determine mean luminosity level
            picgray = rgb2gray(dpic);
            mean(pos) = sum(sum(picgray)) / ij(1) / ij(2);

        end

    end
    save exposuredata.mat ExposureTime FNumber number mean
else % recall saved data
    load exposuredata.mat
end





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sort and reshape to matrix form
srt = sortrows([ExposureTime' FNumber' mean']);

ET = reshape(srt(:,1),8,25);
FN = reshape(srt(:,2),8,25);
LU = reshape(srt(:,3),8,25);

ET = log10(ET); % log x axis for better view

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 3d plot
figure
surfc(ET,FN,LU,'linewidth',2)
xlabel('ExposureTime [s]')
ylabel('ApertureNumber')
zlabel('Exposure')
title('Exposure map EOS 400D (ISO100)')
box on
shading interp

axis([-inf inf -inf inf 0 255]);

% make tricky labels
labels = ExposureTime(25:-1:1);
for i = 1:length(labels)
    names(i) = {sprintf('1/%d',1/labels(i))};
end

names(2:2:24) = {''};

set(gca,'XTick',log10(labels));
set(gca,'XTickLabel',names);
set(gca,'linewidth',1.3);

print -dpng -r200 ExposureMap3D.png

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 2d contour plot
figure
[C,h] = contour(ET,FN,LU,linspace(1,254,24),'linewidth',2);
set(gca,'linewidth',1.3)
clabel(C,h);
grid on
set(gca,'XTick',log10(labels))
set(gca,'XTickLabel',names);

set(gca,'YTick',FNumber(1:25:200))
xlabel('ExposureTime [s]')
ylabel('ApertureNumber')
title('Exposure map EOS 400D (ISO100)')

print -dpng -r200 ExposureMap.png
