close all 

% 1
I = imread('rice.png');
figure, imshow(I);

% 2
background = imopen(I, strel('disk', 15));

figure, imagesc(background, [0 255]), colormap gray; 
set(gca,'ydir','reverse');

% 3
I2 = imsubtract(I, background);
figure, imshow(I2)

% 4
I3 = imadjust(I2);
figure, imshow(I3);

% 5
level = graythresh(I3);
bw = im2bw(I3, level);
figure, imshow(bw);

% 6
[labeled, numObjects] = bwlabel(bw, 4);
numObjects

% 7
rect = [105 125 10 10]; 
grain = imcrop(labeled,rect);
figure, imshow(grain,'InitialMagnification','fit');

% 8 
RGB_label = label2rgb(labeled, @spring, 'c', 'shuffle');
imshow(RGB_label)

% 9 
graindata = regionprops(labeled, 'basic');
graindata(50).Area 

% 10 
allgrains = [graindata.Area];
max_area = max(allgrains);
biggrain = find(allgrains == max_area)
mean(allgrains)

% 11 
nbins = 20;
figure, hist(allgrains, nbins)

% 12 
grainorientations = regionprops(labeled, 'Orientation','Centroid');
orientations = [grainorientations.Orientation];

figure, imshow(I)
hold on
for k = 1:length(orientations)
    o = orientations(k); 
    centroid = grainorientations(k).Centroid;
    
    if -20 < o & o < 20
        text(centroid(1)+1, centroid(2)+1, sprintf("%2.2f",o), 'Color', 'y', ... 
            'FontSize', 9, 'FontWeight', 'bold');
        plot(centroid(1), centroid(2), 'yo')
    end
    
    %also im showing vertical grains here
     if o > 85
        text(centroid(1)+1, centroid(2)+1, sprintf("%2.2f",o), 'Color', 'y', ... 
            'FontSize', 9, 'FontWeight', 'bold');
        plot(centroid(1), centroid(2), 'yo')
     end
    if o < -85 
        text(centroid(1)+1, centroid(2)+1, sprintf("%2.2f",o), 'Color', 'y', ... 
            'FontSize', 9, 'FontWeight', 'bold');
        plot(centroid(1), centroid(2), 'yo')
    end
    
end

