MATLAB: How to code the total pixels number and white pixels and black area pixels number

Image Processing Toolboxpixels

how to code the total pixels number and white pixels and black area pixels number. If I just need half image how to do that? I'm learner in matlab. thanks
[fname path]=uigetfile('*.png','select an image');
fname=strcat(path,fname);
im=imread(fname);
imshow(im);
numWhitePixels = sum(im(:));
numPixels = sum(im(:));

Best Answer

Try this:
[baseName, folder]=uigetfile('*.png','select an image');
fullFileName = fullfile(folder, baseName);
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
% It's not really gray scale like we expected - it's color.
% Use weighted sum of ALL channels to create a gray scale image.
grayImage = rgb2gray(grayImage);
% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
% which in a typical snapshot will be the least noisy channel.
% grayImage = grayImage(:, :, 2); % Take green channel.
end
% Display the image.
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', 20, 'Interpreter', 'None');
% Assuming grayImage is a binary image...
numWhitePixels = nnz(grayImage); % Sum of non-zero pixels.
numPixels = numel(grayImage);
numBlackPixels = numPixels - numWhitePixels