clear all;
MAP=imread('Image001-Map.png'); %read in map image (possibly change for another image if it works better
binary=MAP>0; %convert to binary (may need to increase cut-off above zero)
leafDiscs=imfill(binary,'holes'); %any holes 
CC=bwconncomp(leafDiscs);
numPixels=cellfun(@numel,CC.PixelIdxList);
threshold = 10; %threshold colony pixelnumber, adjust if necessary
for i=1:numel(numPixels)
    if numPixels(i)<threshold
        leafDiscs(CC.PixelIdxList{i})=0;
    end
end
        
label=bwlabel(leafDiscs);
labelSort=zeros(max(max(label)),4);
for j=1:max(max(label))
    [row,col] = find(label==j);
    len=max(row)-min(row);
    meanRow=mean(row);
    meanCol=mean(col);
    breadth=max(col)-min(col);
    target=uint8(zeros([len breadth]));
    sy=min(col)-1;
    sx=min(row)-1;
    labelSort(j,:)=[j,meanRow,meanCol,1.5*meanRow+25*meanCol];

    %check: plot by region
%     for i=1:size(row,1)
%         x=row(i,1)-sx;
%         y=col(i,1)-sy;
%         target(x,y)=MAP(row(i,1),col(i,1));
%     end
%     mytitle=strcat('Object Number:',num2str(j));
%     imshow(target); title(mytitle);
end
%sort by rows and columns starting from top left corner moving down to allow easy mapping to plots and genotypes from spreadsheet
[RowsSorted,ix]=sortrows(labelSort,4); 
imshow(leafDiscs)
for i=1:numel(RowsSorted(:,1))
    text(RowsSorted(i,3)-5,RowsSorted(i,2), num2str(RowsSorted(i,1)))
end
    
    
