How can I determine the cluster of pixels in an image that are red or green and quantify how many of the clusters are green or red?

21 views (last 30 days)
I have an image that has small red or green circles per image. Each image could have up to 30 or so red or green circles per image. I have to count them manually in order to quantify them and it can be tedious with more than 50 images. Is there a way to classify the circles as red or green and then quantify them by color automatically? Thanks!
  42 Comments
Neo
Neo on 6 Jul 2022
Yes, but once I upload my images (just two to test) it outputs:
filename circle_count
___________ ____________
{1×29 cell} 1×29 double

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 23 Jun 2022
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1036195/image.jpeg';
YourRGBImage = imread(filename);
bw = im2bw(YourRGBImage);
bw = bwareafilt(bw, [10 inf]);
whos bw
Name Size Bytes Class Attributes bw 512x512 262144 logical
[~, numcircles] = bwlabel(bw) ;
imshow(YourRGBImage)
imshow(bw)
numcircles
numcircles = 9

More Answers (2)

Image Analyst
Image Analyst on 22 Jun 2022
Try this. It should work for any color spots.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
%===============================================================================
% Get the name of the image the user wants to use.
baseFileName = 'green spots.png';
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)
% Crop off screenshot stuff
% rgbImage = rgbImage(132:938, 352:1566, :);
% Display image.
subplot(2, 2, 1);
imshow(rgbImage, []);
impixelinfo;
axis on;
caption = sprintf('Original Color Image\n%s', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% 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;
% Take one of the color channels, whichever one seems to have more contrast.
grayImage = max(rgbImage, [], 3);
% Crop away white surrounding frame.
% It's probably there because it's not the original image but came from a screenshot of a figure.
grayImage = grayImage(33:385, 123:475);
% Get the updated dimensions of the image.
[rows, columns, numberOfColorChannels] = size(grayImage)
% Display the image.
subplot(2, 2, 2);
imshow(grayImage, []);
title('Gray Scale Image', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
%=======================================================================================
% Show the histogram
subplot(2, 2, 3);
imhist(grayImage);
grid on;
caption = sprintf('Histogram of Gray Scale Image')
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Gray Level', 'FontSize', fontSize)
ylabel('Count', 'FontSize', fontSize)
%=======================================================================================
% Threshold the image to get the disk.
lowThreshold = 43;
highThreshold = 255;
% Use interactive File Exchange utility by Image Analyst to to the interactive thresholding.
% https://www.mathworks.com/matlabcentral/fileexchange/29372-thresholding-an-image?s_tid=srchtitle
% [lowThreshold, highThreshold] = threshold(114, 255, grayImage);
mask = grayImage >= lowThreshold & grayImage <= highThreshold;
xline(lowThreshold, 'Color', 'r', 'LineWidth',2);
xline(highThreshold, 'Color', 'r', 'LineWidth',2);
% Find out the size of all the blobs so we know what size to use when filtering with bwareaopen.
props = regionprops(mask, 'Area');
allAreas = sort([props.Area]);
% Now do clean up by hole filling, and getting rid of small blobs.
mask = bwareaopen(mask, 100); % Take blobs larger than 100 pixels only.
% Display the color segmentation mask image.
subplot(2, 2, 4);
imshow(mask, []);
title('Final Mask', 'FontSize', fontSize, 'Interpreter', 'None');
impixelinfo;
axis('on', 'image');
drawnow;
% Find out the size of all the remaining blobs.
props = regionprops(mask, 'Area');
allAreas = sort([props.Area])
areaFraction = sum(allAreas) / numel(mask)
uiwait(helpdlg('Done!'));

james
james on 8 Jul 2022
Does the classifier make clusters on red,green and blue channel separately? And if it does- lets say the cluster are formed at intensities 40,80,90,135 for red 60,90,130,240 for green 20,40,60,90 for blue.
  4 Comments
Image Analyst
Image Analyst on 16 Aug 2022
@Neo the classification code I gave will work for any color (not just green). The color does not even have to lie solely in one particular color channel. For example the color could be [.3, 0.5, 0.8] and it would still find it because you train it by telling it (by outlining a region) what color(s) you are looking for. THe discriminant analysis is a statistical color classifier. If you just want to use known color ranges, that are fixed and known in advance, then you might want to use the Color Thresholder app because with that tool you do not need to outline any regions to tell it the colors. You tell it the colors by thresholding the histograms.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!