% -----------------------------------------------------
% image_colortobw.m
% -----------------------------------------------------
% Write a program that reads an image file, converts it 
% to black and white and writes it into another file. 
% -----------------------------------------------------
% Notes: The image files used must be in the same folder
% as the program. 
% -----------------------------------------------------
% Copyright and license details available at matlabmarina.com
%------------------------------------------------------
clear
clc
close all

% Read the original image and 'plot' it
[originalimage,originalmap] = imread('sciencecenter.jpg');
figure
image(originalimage);
axis off

% Define threshold intensity
threshold = 125;

% Obtain the image size
[M,N,clrs] = size(originalimage);     
% N is number of columns (width)         % M is number of rows (height)

% Convert image to type double for MATLAB operations
tempimage = double(originalimage);

% Create space for the lightened image
filteredimage = zeros(M,N,3);

% Convert to black and white
% The image is converted to black and white by making all pixels with
% intensity greater than threshold white and all others black

% Compute the average of all color intensities
temp1 = (tempimage(:,:,1) + tempimage(:,:,2) + tempimage(:,:,3))/3; 
% Compare this with the threshold
temp2 = temp1 > threshold;
% Convert to a range from 0-255
filteredimage(:,:,1) = 255 * double(temp2);

% Set all layers in the new image to be the same black & white intensity
filteredimage(:,:,2) = filteredimage(:,:,1);
filteredimage(:,:,3) = filteredimage(:,:,1);

% Convert image back to type uint8
newimage = uint8(filteredimage);

figure
image(newimage);
axis off

% Save the processed image
imwrite(newimage,'outimage.jpg');
