% Show the conversion of a color image to grayscale image

close all

% Convert jpg image to 3D uint8 array and determine its dimensions
A= imread('LawSchool.jpg');
[nr,nc,np]= size(A);

% Set up a big figure and display the image
figure
set(gcf,'position',[50 50 800 600])
image(A); axis off
shg
pause % wait until user presses a key

% Convert to grayscale
B1= zeros(nr,nc);
B1= uint8(B1); % Type for image color values
B2= B1;
for r= 1:nr
for c= 1:nc
ave1= A(r,c,1)*0.299 + A(r,c,2)*0.587 + A(r,c,3)*0.114;
ave2= A(r,c,1)/3 + A(r,c,2)/3 + A(r,c,3)/3; % this is correct
% ave2= (A(r,c,1)+A(r,c,2)+A(r,c,3))/3; % this is wrong!
B1(r,c)= ave1;
B2(r,c)= ave2;
end
end

% Display the two gray images, then store 3-d array data (B1) as jpg image
figure
imshow(B1); title('Weighted Average','Fontsize',16,'Fontweight','bold'); axis off
shg
figure
imshow(B2); title('Average','Fontsize',16,'Fontweight','bold'); axis off
%imwrite(B1,'LawSchoolGray.jpg')