Color Thresholding in the RGB or HSV space

78 views (last 30 days)
Hello, I have to work with the color image attached below. Maybe it's not very visible but in the middle of the black blob there's a coloured dot.
What I have to do is to threshold the image in order to obtain a binary map with the value ''1'' in correspondence of the dot and ''0'' in the rest of the image. Then, by calculating the center of mass of the ''1'' pixels, I have to extract the coordinates of the dot position.
Do you know how I could do that?
Thank you in advance.

Accepted Answer

Image Analyst
Image Analyst on 14 Nov 2020
Edited: Image Analyst on 14 Nov 2020
Federica, use the Color Thresholder (Apps tab or tool ribbon) to get a binary image of red stuff. Export the code and put it into your main program. Then if you know it's small, use bwareaopen() or bwareafilt() to get rid of bigger blobs. If there are still small red specks, then you might have to first find the mask for the black blob and multiply the black mask by the red mask to get only red blobs inside the black blob. That should find you all small red blobs inside the black blob. Then call regionprops() to get its centroid, area, or whatever else you need to know about it. Not hard at all.
Let me know if you can't figure it out.
EDIT: Alright, here's a start:
% Demo to find red dots. By Image Analyst, Nov. 14, 2020.
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;
fprintf('Beginning to run %s.m ...\n', mfilename);
% Read in image.
folder = [];
baseFileName = 'image.jpeg';
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);
% It's not an RGB image! It's an indexed image, so read in the indexed image...
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display the test image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Image : "%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.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% 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.
hFig1.Name = 'Demo by Image Analyst';
[mask, maskedRGBImage] = createMask(rgbImage);
% Display the initial mask image.
subplot(2, 2, 2);
imshow(maskedRGBImage, []);
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
axis('on', 'image');
title('Masked RGB Image', 'FontSize', fontSize, 'Interpreter', 'None');
% See what areas we have initially.
props = regionprops(mask, 'Area');
allAreas = [props.Area]
% Display the initial mask image.
subplot(2, 2, 3);
imshow(mask, []);
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
axis('on', 'image');
title('Initial Mask', 'FontSize', fontSize, 'Interpreter', 'None');
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
% Clean up the mask to get rid of red things that we don't want.
% Take just the smallest regions:
mask = bwareafilt(mask, [1, 200]);
% Display the final masked image.
subplot(2, 2, 4);
imshow(maskedRgbImage, []);
axis('on', 'image');
title('Final Mask', 'FontSize', fontSize, 'Interpreter', 'None');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Make measurements on the final blobs
props = regionprops(mask, 'Area', 'Centroid');
allAreas = [props.Area]
xy = vertcat(props.Centroid)
% Draw circles around them.
hold on
for k = 1 : length(props)
plot(xy(k, 1), xy(k, 2), 'yo', 'MarkerSize', 15, 'LineWidth', 2);
caption = sprintf(' (x,y) = (%.1f, %.1f). Area = %d', xy(k, 1), xy(k, 2), allAreas(k));
text(xy(k, 1), xy(k, 2), caption, 'Color', 'y');
hold off;
fprintf('Done running %s.m ...\n', mfilename);
function [BW,maskedRGBImage] = createMask(RGB)
%createMask Threshold RGB image using auto-generated code from colorThresholder app.
% [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
% auto-generated code from the colorThresholder app. The colorspace and
% range for each channel of the colorspace were set within the app. The
% segmentation mask is returned in BW, and a composite of the mask and
% original RGB images is returned in maskedRGBImage.
% Auto-generated by colorThresholder app on 14-Nov-2020
% Convert RGB image to chosen color space
I = rgb2lab(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.000;
channel1Max = 69.558;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 19.834;
channel2Max = 48.368;
% Define thresholds for channel 3 based on histogram settings
channel3Min = -27.130;
channel3Max = 29.189;
% Create mask based on chosen histogram thresholds
sliderBW = (I(:,:,1) >= channel1Min ) & (I(:,:,1) <= channel1Max) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
% Initialize output masked image based on input image.
maskedRGBImage = RGB;
% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;
Fed on 15 Nov 2020
Thanks again. Now it's clear!

Sign in to comment.

More Answers (0)


Find more on Image Processing Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!