code for calculating the percentage of the bluer image in matlab

main.m
% read in the image
im = imread('blueimage.jpg');

% convert the image from RGB to LAB color space
imLab = rgb2lab(im);

% define the blue color threshold in LAB color space
blueThreshold = [15, 0, -15];

% create a binary mask of the blue pixels
imBluePixels = all(bsxfun(@gt, imLab, blueThreshold), 3);

% calculate the area of the blue pixels
blueArea = sum(imBluePixels(:));

% calculate the percentage of the blue pixels
totalPixels = numel(imBluePixels);
bluePercentage = 100 * blueArea / totalPixels;

fprintf('The blue image is %.2f%% blue.\n', bluePercentage);
570 chars
21 lines

Explanation:

  1. We first read in the image using the imread function.
  2. Next, we convert the image from RGB to LAB color space using rgb2lab function. This is because the L and B channels in the LAB color space are useful for color segmentation.
  3. We set a threshold value blueThreshold in LAB color space for blue color.
  4. We create a binary mask imBluePixels of the blue pixels by comparing each pixel color to the blue threshold using bsxfun function.
  5. We calculate the area of the blue pixels by summing up all the elements in the binary mask.
  6. Finally, we calculate the percentage of the blue pixels in the image by dividing the blue area by the total number of pixels in the image and multiplying by 100.

gistlibby LogSnag