%The code for the MATLAB algorithm for culculaing the pod shell thickness.
clear;
A1 = imread('F:/matlab/.tif2/81 82 83 85 86.tif');
A2 = imread('F:/matlab/.png2/81 82 83 85 86.png');
B = rgb2gray(A2);
C = im2bw(B,0.95);
D1 = bwareaopen(C,10000);
D2 = imcomplement(bwareaopen(imcomplement(D1),100));
inner = edge(D2);
E = im2bw(B,0.1);
E1 = bwareaopen(E,10000);
outer = imcomplement(bwareaopen(imcomplement(E1),1000));
outer = edge(outer);

scale = 208.96/4936;
row = [40,1450,2800,4050,5300,6800];
column = [75,950,1650,2500,3200,4000,4740];
s1 = 0;
s2 = 0;
x1 = zeros(1,1);
x2 = zeros(1,1);
y1 = zeros(1,1);
y2 = zeros(1,1);
[m,n] = size(B);
thickness = zeros(5,6);

imshow(A1);hold on;
for rn = 1:5 
    for cn = 1:6 
        for i = row(rn):row(rn+1)
            for j = column(cn):column(cn+1)
                if(outer(i,j)==1)
                    s1 = s1+1;
                    x1(s1) = i;
                    y1(s1) = j;
                end
                if(inner(i,j)==1)
                    s2 = s2+1;
                    x2(s2) = i;
                    y2(s2) = j;
                end
            end
        end
        
        p = zeros(s1,1);
        q = zeros(s2,1);

        if(s1==0)
            p = zeros(1,1);
        end
        if(s2==0)
            q = zeros(1,1);
        end
        
        
        for i = 1:s1 
            for j = 1:s2 
                q(j) = sqrt((x1(i)-x2(j)).^2+(y1(i)-y2(j)).^2);
            end
            [p(i),subscript] = min(q);      
            plot([y1(i) y2(subscript)], [x1(i) x2(subscript)],'Color','r','LineWidth',1)
        end
        
        thickness(rn, cn) = sum(p)/s1*scale;
        s1 = 0;
        s2 = 0;
    end
end


for rn = 1:5
    for cn = 1:6
        if (thickness(rn, cn)==0)
            thickness(rn, cn) = nan;
        end
    end
end
pst = nanmean(thickness,2);

