How to threshold and obtain RGB and reflactance values (max, min, mean) of MULTIPLE images?

9 views (last 30 days)
Hi! I have several '.tif' photos of seeds that I would like to threshold to obtain RGB values (max, min, mean) and reflectance values (max, min, mean) of individual images and, if it's possible, individual seeds. I used to do this on ImageJ but I need to learn it on MatLab.
I manually set up the channels thresholds with the Color Thresholder app and generated a function, but honestly I have not had success using this function in a loop. I would eventually like to have a .csv file with columns: "image, seed, red_max, red_min, red_mean, green_max, green_min, green_mean, blue_max, blue_min, blue_mean..." and the same for reflectance.
This is what my images look like.
I'd really appreciate any help you guys could provide me!
Cheers!
Joan.

Accepted Answer

Image Analyst
Image Analyst on 19 Aug 2017
Try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 25;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'Seeds.jpg';
% Get the full filename, with path prepended.
folder = pwd
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
%===============================================================================
% Read in demo image.
rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(rgbImage);
% Display the original image.
subplot(1, 2, 1);
imshow(rgbImage, []);
axis on;
caption = sprintf('Original Color Image, %s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo();
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Threshold to create a mask.
binaryImage = redChannel > 90;
% Get rid of small noise blobs.
binaryImage = bwareafilt(binaryImage, [100, inf]);
% Erode them a bit to separate touching ones and get away from light shadows.
se = strel('disk', 7, 0);
binaryImage = imerode(binaryImage, se);
% Display the mask image.
subplot(1, 2, 2);
imshow(binaryImage, []);
axis on;
caption = sprintf('Seed Mask');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo();
[labeledImage, numSeeds] = bwlabel(binaryImage);
propsR = regionprops(labeledImage, redChannel, 'MeanIntensity', 'PixelValues');
propsG = regionprops(labeledImage, greenChannel, 'MeanIntensity', 'PixelValues');
propsB = regionprops(labeledImage, blueChannel, 'MeanIntensity', 'PixelValues');
allMeansR = [propsR.MeanIntensity];
allMeansG = [propsG.MeanIntensity];
allMeansB = [propsB.MeanIntensity];
overallSeedMeanR = mean(allMeansR);
overallSeedMeanG = mean(allMeansG);
overallSeedMeanB = mean(allMeansB);
% Get min and max of each seed for each color channel
for k = 1 : numSeeds
allMinsR(k) = min(propsR(k).PixelValues);
allMinsG(k) = min(propsG(k).PixelValues);
allMinsB(k) = min(propsB(k).PixelValues);
allMaxsR(k) = max(propsR(k).PixelValues);
allMaxsG(k) = max(propsG(k).PixelValues);
allMaxsB(k) = max(propsB(k).PixelValues);
end
% Prepare data for csvwrite
% "image, seed, red_max, red_min, red_mean, green_max, green_min, green_mean, blue_max, blue_min, blue_mean..."
data = [(1:numSeeds)', allMaxsR', allMinsR', allMeansR', allMaxsG', allMinsG', allMeansG', allMaxsB', allMinsB', allMeansB']
% csvwrite can't handle strings, only numbers. If you want the filenames on each line, use xlswrite().
% Get the name of the file that the user wants to save.
% Note, if you're saving an image you can use imsave() instead of uiputfile().
startingFolder = userpath; % Or "pwd" or wherever you want.
defaultFileName = fullfile(startingFolder, '*.csv');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
csvwrite(filename, data);
  1 Comment
JoanManBar
JoanManBar on 20 Aug 2017
Edited: per isakson on 2 Dec 2017
Thank you so much for your answer and code, it is AMAZING! I hope it's not too much to ask but could you help me a little to understand how to do this for multiple photos? After several hours trying, I gave up. I guess I'm just not good at making loops -any recommendation to learn is always welcome.
This is my poor attempt:
%%Clean and format
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 25;
%%Define variables
imagefiles = dir('*.tif');
filenames = {imagefiles.name};
nfiles = length(imagefiles);
%%===============================================================================
% % Get the name of the image the user wants to use.
% baseFileName = 'c_sample001.tif';
% % Get the full filename, with path prepended.
% folder = pwd
% fullFileName = fullfile(folder, baseFileName);
%%Check if file exists.
% if ~exist(fullFileName, 'file')
% % The file doesn't exist -- didn't find it there in that folder.
% % Check the entire search path (other folders) for the file by stripping off the folder.
% fullFileNameOnSearchPath = baseFileName; % No path this time.
% if ~exist(fullFileNameOnSearchPath, 'file')
% % Still didn't find it. Alert user.
% errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
% uiwait(warndlg(errorMessage));
% return;
% end
% end
%%Functions
for ii = 1:nfiles
currentfilename = imagefiles(ii).name;
currentimage = imread(currentfilename);
images = currentimage;
% Read in demo image.
% rgbImage = imread(fullFileName);
% Get the dimensions of the image.
[rows, columns, numberOfColorChannels] = size(images);
% Display the original image.
subplot(1, 2, 1);
imshow(images, []);
axis on;
caption = sprintf('Original Color Image, %s', currentfilename);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo();
% ---
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0.05 1 0.95]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
for i = 1:length(images)
% Extract the individual red, green, and blue color channels.
redChannel = images(:, :, 1);
greenChannel = images(:, :, 2);
blueChannel = images(:, :, 3);
end
% Threshold to create a mask.
binaryImages = redChannel(ii) > 90;
% Get rid of small noise blobs.
binaryImages = bwareafilt(binaryImages, [100, inf]);
% Erode them a bit to separate touching ones and get away from light shadows.
se = strel('disk', 7, 0);
binaryImages = imerode(binaryImages, se);
% Display the mask image.
subplot(1, 2, 2);
imshow(binaryImages, []);
axis on;
caption = sprintf('Seed Mask');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo();
% -
[labeledImages, numSeeds] = bwlabel(binaryImages);
propsR = regionprops(labeledImages, redChannel, 'MeanIntensity', 'PixelValues');
propsG = regionprops(labeledImages, greenChannel, 'MeanIntensity', 'PixelValues');
propsB = regionprops(labeledImages, blueChannel, 'MeanIntensity', 'PixelValues');
allMeansR = [propsR.MeanIntensity];
allMeansG = [propsG.MeanIntensity];
allMeansB = [propsB.MeanIntensity];
overallSeedMeanR = mean(allMeansR);
overallSeedMeanG = mean(allMeansG);
overallSeedMeanB = mean(allMeansB);
Get min and max of each seed for each color channel
for k = 1 : numSeeds
allMinsR(k) = min(propsR(k).PixelValues);
allMinsG(k) = min(propsG(k).PixelValues);
allMinsB(k) = min(propsB(k).PixelValues);
allMaxsR(k) = max(propsR(k).PixelValues);
allMaxsG(k) = max(propsG(k).PixelValues);
allMaxsB(k) = max(propsB(k).PixelValues);
end
% Prepare data for csvwrite
% "image, seed, red_max, red_min, red_mean, green_max, green_min, green_mean, blue_max, blue_min, blue_mean..."
data = [(1:numSeeds)', allMaxsR', allMinsR', allMeansR', allMaxsG', allMinsG', allMeansG', allMaxsB', allMinsB', allMeansB']
% csvwrite can't handle strings, only numbers. If you want the filenames on each line, use xlswrite().
% Get the name of the file that the user wants to save.
% Note, if you're saving an image you can use imsave() instead of uiputfile().
startingFolder = pwd; % Or "pwd" or wherever you want.
defaultFileName = fullfile(startingFolder, '*.csv');
[images, folder] = uiputfile(defaultFileName, 'Specify a file');
if images == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, images)
csvwrite(filename, data);
end

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!