% SceneprocessingTransTest.m
% Reads in a .png file, sets it up as 256x256, and filters it for VisNet or VisScene
% Derived from ALOIprocessing3_v2.m
% If the file is from Illustrator, export the .png with a black background
% Scripts to normalise and filter the ALOI dataset
% - filtering by selecting angles
% This version places a bounding box around the object (red in figure(1)),
% enlarges it by enlargement (blue in figure(1) to allow for some views being larger; 
% centres the image, scale it to 256x256, and adjusts its contrast.
% It is important that the same enlargement and centering is used for all views of an object

% ALOIprocessing_v2.m Oct 2020 updates the code for parpool, and tests histeq as a
% possible alternative to imadjust()

clear all; close all hidden; format compact;
%                     f_filt = fopen(strcat(image_dir, image_name,'.filt'), 'r');
%rotList = [10:20:355];

%poolobj = parpool('local',8); % It is probably best to issue this before you run the program
                               % if you wish to use the parfor below.
                               
%dataPath = '/home/leigh/Desktop/PhDProject/ProcessedImages/ALOI2';
%dataPath = '/home/erolls/imagedata/ALOI';
%dataPath = '/home/erolls/imagedata/ALOItmp';
%dataPath = 'C:\imagedata\ALOI_79';
dataPath = 'C:\imagedata\Scenes';
scenestr = 'scene3'; % set the filename here

dirs = dir(dataPath);
catNames = {dirs([dirs.isdir]).name};
catNames = setdiff(catNames, {'.', '..'});

tStart = tic;

N_VIEWS_TEST = 9; % NOT a global variable. Set this

Xoffset_indexing = [];
Yoffset_indexing = [];
counter = 0;
if N_VIEWS_TEST == 9
    row_total = 3;
    col_total = 3;
else
    row_total = 10;
    col_total = 10;
end

for row = 1 : row_total
    for col = 1 : col_total
        counter = counter + 1;
        Xoffset_indexing(counter) = row;
        Yoffset_indexing(counter) = col;
    end
end
Xoffset = Xoffset_indexing * 0;
Yoffset = Yoffset_indexing * 0;

toparray = []; 
leftarray = [];
toparray_indexing = []; 
leftarray_indexing = [];
counter = 0;
for row = 1 : row_total
    for col = 1 : col_total
        counter = counter + 1;
        leftarray(counter) = (row - 1) * floor(256/row_total) + 1; % (256 - 45) / (3-1)
        toparray(counter) = (col - 1) * floor(256/col_total) + 1;
        leftarray_indexing(counter) = row;
        toparray_indexing(counter) = col;
    end
end
try
    file = ['C:\imagedata\Scenes\', scenestr, '.png'] % EDIT THE FILENAME HERE of the image to be read
catch
    file = ['C:\imagedata\Scenes\', scenestr, '.jpg'] % EDIT THE FILENAME HERE of the image to be read
end

for i = 1: numel(Xoffset)
    %files = dir(fullfile(dataPath, catNames{i}, '*.png'));
    %files = {files.name};    
    %file = [ fullfile(dataPath, catNames{i}) '/' catNames{i} '_r' int2str(rotList(1)) '.png' ]
    if Xoffset_indexing(i) < 0
        strx = strcat('n', int2str(abs(Xoffset_indexing(i))));
    else
        strx = int2str(Xoffset_indexing(i));
    end
    if Yoffset_indexing(i) < 0
        stry = strcat('n', int2str(abs(Yoffset_indexing(i))));
    else
        stry = int2str(Yoffset_indexing(i));
    end
    %fileout = strcat('scene2_Xoffset', strx, '_Yoffset', stry, '.png') % for the file to be created
    fileout = strcat(scenestr, '_Xoffset', strx, '_Yoffset', stry) % for the file to be created

    tmp = imread(file);
    size(tmp);
    tmp = imcomplement(tmp);
%     max(max(tmp(:,:,1)))
%     min(min(tmp(:,:,1)))
    tmp = rgb2gray(tmp);
    size(tmp);
    max(max(tmp));
    min(min(tmp));
    figure(1)
    imshow(tmp);
%     st = regionprops(double(tmp > 30), 'BoundingBox');
%     rect = st.BoundingBox % xmin ymin width height
%     figure(1);
%     imshow(tmp); hold on;
%     rectangle('Position', rect, 'EdgeColor', 'r');
%     enlargement = 20; % aim for this as some views may be larger than the first, but clip as necessary
%     rect(1) = rect(1) - enlargement; % xmin
%     if rect(1) < 1; rect(1) = 1; end
%     rect(3) = rect(3) + (enlargement * 2); % width
%     if rect(3) + rect(1) > size(tmp, 2); rect(3) = size(tmp, 2) - rect(1); end
%     rect(2) = rect(2) - enlargement; % ymin
%     if rect(2) < 1; rect(2) = 1; end % y = 1 is the top of the image
%     rect(4) = rect(4) + (enlargement * 2); % width
%     if rect(4) + rect(2) > size(tmp, 1); rect(4) = size(tmp, 1) - rect(2); end
%     rect    
%     rectangle('Position', rect, 'EdgeColor', 'b');
%     tmp1 = imcrop(tmp, rect);
%     size(tmp1)
%     figure(10);
%     imshow(tmp1);
%     % now resize to a max dim of 256
%     m = max(rect(3),rect(4))
%     tmp2 = imresize(tmp1, [(rect(4) * 256 / m) (rect(3) * 256 / m)]);

    tmp2 = imresize(tmp, [256 256]);
    size(tmp2);
    figure(2);
    imshow(tmp2);


%     x = size(tmp2,2)
%     c1 = floor(128 - x/2)
%     if c1 < 1; c1 = 1; end
%     if c1 > 256; c1 = 256; end
%     y = size(tmp2,1)
%     r1 = floor(128 - y/2)
%     if r1 < 1; r1 = 1; end
%     if r1 > 256; r1 = 256; end
%     tmp3 = uint8(zeros(256, 256));
%     %tmp3(r1 : r2, c1 : c2) = tmp2;
%     tmp3(r1 : (r1 + size(tmp2, 1) -1), c1 : (c1 + size(tmp2, 2) - 1)) = tmp2;
    tmp3 = uint8(tmp2);
    size(tmp3);
    figure(3);
    imshow(tmp3);
    fid = fopen(['c:/imagedata/Scenes/',scenestr], 'w');
    fwrite(fid, tmp3', '*uint8');
    fclose(fid);
    top_indexing = toparray_indexing(i);
    left_indexing = leftarray_indexing(i);
    top = toparray(i);
    left = leftarray(i);
    FilterConv6(scenestr, fileout, 'c:/imagedata/Scenes/', 0, Xoffset(i), Yoffset(i), left, top); % left, top is where the extracted image should be translated to
end

% 
%     %pause
%     tmp3 = imadjust(tmp3, stretchlim(tmp3)); % set min=0 max=255 with 1% saturation at each end
%     %tmp3 = histeq(tmp3); % an alternative to imadjust which is not as useful
%     figure(4);
%     imshow(tmp3);
%     drawnow
%     for j = 1:1 %numel(rotList) % a check on the image cropping etc       
%         %file = [ fullfile(dataPath, catNames{i}) '\' catNames{i} '_r' int2str(rotList(j)) '.png' ]
%         tmp = imread(file);
%         tmp1 = imcrop(tmp, rect);
%         tmp2 = imresize(tmp1, [(rect(4) * 256 / m) (rect(3) * 256 / m)]);
%         tmp3 = uint8(zeros(256, 256));
%         tmp3(r1 : (r1 + size(tmp2, 1) -1), c1 : (c1 + size(tmp2, 2) - 1)) = tmp2;
%         tmp = imadjust(tmp3, stretchlim(tmp3)); % set min=0 max=255 with 1% saturation at each end
%         figure(10+j);
%         imshow(tmp);
%         drawnow;
%         filecropped = cropped.png; % [ fullfile(dataPath, catNames{i}) '/' catNames{i} '_r' int2str(rotList(j)) 'cropped.png' ];
%         imwrite(tmp, filecropped); % This writes the cropped and contrast adjusted image as a .png to the output as an easy data check. Comment out if not needed.
%     end
%     %pause
%     %parfor j = 1:numel(rotList)
%     for j = 1:1 %numel(rotList)
%         %file = [ fullfile(dataPath, catNames{i}) '/' catNames{i} '_r' int2str(rotList(j)) '.png' ]
%         tmp = imread(file);    
%         tmp1 = imcrop(tmp, rect);
%         tmp2 = imresize(tmp1, [(rect(4) * 256 / m) (rect(3) * 256 / m)]);
%         tmp3 = uint8(zeros(256, 256));
%         tmp3(r1 : (r1 + size(tmp2, 1) -1), c1 : (c1 + size(tmp2, 2) - 1)) = tmp2;
%         tmp = imadjust(tmp3, stretchlim(tmp3)); % set min=0 max=255 with 1% saturation at each end
%         [a b c] = fileparts(fullfile(file));
%         % fid = fopen(fullfile(a,[ b '.dat' ]), 'w');
%         fid = fopen(fullfile(a,[b]), 'w');
%         fwrite(fid, tmp', '*uint8');
%         fclose(fid);
%         %FilterConv4([b '.dat'], [ fullfile(dataPath, catNames{i}) '/' ], 0);
%         %[ fullfile(dataPath, catNames{i}) '/' ]
%         FilterConv4([b], [ fullfile(dataPath, catNames{i}) '/' ], 0);
%         FilterConv4([b], 'c:/imagedata/Scenes/', 0);
% 
%     end
% end
% tEND = toc(tStart)
% poolobj = gcp('nocreate'); % If no pool, do not create new one.
% if isempty(poolobj)
%     poolsize = 0
% else
%     poolsize = poolobj.NumWorkers
% end
% %delete(poolobj)
% 
