% images processing demo code for matlab class 2014-09-11
%
% code modified from http://www.instructables.com/id/Image-Processing-and-Counting-using-MATLAB/
%
close all

%Step 1: Read the Image
image_file='Lines.jpg';
%image_file='calcium.jpg';
%image_file='2013_08_13_ivar_030.JPG';

img1=imread(image_file);

% learn more about image processing:
help images

% display the figure
figure
imshow(img1)

% color images are 3-d matrices:
size(img1)

% look at the red plane:
timg=img1;
timg(:,:,2:3)=0;
imshow(timg);

% look at the blue plane:
timg=img1;
timg(:,:,1:2)=0;
imshow(timg);

%Step 2: Convert the Image to Grayscale

% This step removes any color information in the image to make it easier to
% identify objects. The rgb2gray converts the color image into a grayscale
% image and stores it into the matrix img2.

img1=rgb2gray(img1);
imshow(img1);

% now it's a 2-d matrix:
size(img1)


%Step 3: Threshold the image

% This step thresholds the image by converting the grayscale image into an
% image that contains only two colors. The function im2bw() assigns black
% color to all the pixels that have luminosity than a threshold level and
% the others as white. the function graythresh() approximately calculates
% the threshold of the image.

thresh=graythresh(img1);
% this function rescales the image to have values from zero (black) or one
% (white)
img2=im2bw(img1,thresh);
imshow(img2)


% Step 4: Complement the image

% In this step we complement the image by using the ~ operator. By this we
% convert the white patches into black and vice versa. We perform this step
% as we wanted the areas of concern(objects) to be colored white.

img2=~img2;
imshow(img2)

% Step 5: Find the Boundaries of the Objects

% This step finds the boundaries of each object that it finds and stores it
% in B. The text function prints the number of objects that are found by
% bwboundaries.  

B = bwboundaries(img2);
imshow(img2)
text(10,10,strcat('\color{green}Objects Found:',num2str(length(B))))

% Step 6: Draw the Boundaries

% This is a fun step in which we mark the boundaries of all the objects
% identified by bwboundaries function. This step can be eliminated if it
% seems complicated  

hold on
for k = 1:length(B)
    boundary = B{k};
    plot(boundary(:,2), boundary(:,1), 'g', 'LineWidth', 2)
end

%% A few other things to try for fun

% fancy edge detectors
BW1 = edge(img2,'prewitt');
BW2 = edge(img2,'canny');
figure;
subplot(1,2,1);
imshow(BW1);
title('prewitt');

subplot(1,2,2);
imshow(BW2)
title('canny');


% do some wacky things:
figure;

palette_steps=100;
timg=double(img1)./double(max(img1(:)));
for ii=1:palette_steps,
    timg=mod(timg,1)+1./palette_steps;
    imshow(timg);
    drawnow;
end

% even more wacky
timg=double(imread(image_file));
timg=timg./max(timg(:));
for ii=1:palette_steps,
    timg(:,:,1)=mod(timg(:,:,1),1)+1./palette_steps;
    imshow(timg);
    drawnow;
end


