MATLAB: How to define the red, green, and blue Threshold value

color extractionimage segmentation

% Demo macro to very, very simple color detection in RGB color space
% by ImageAnalyst
clc;
close all;
% Read standard MATLAB demo image.
rgbImage = imread('onion.png');
% Display the original image.
subplot(3, 4, 1);
imshow(rgbImage);
title('Original RGB Image');
% Maximize figure.
set(gcf, 'Position', get(0, 'ScreenSize'));
% Split the original image into color bands.
redBand = rgbImage(:,:, 1);
greenBand = rgbImage(:,:, 2);
blueBand = rgbImage(:,:, 3);
% Display them.

subplot(3, 4, 2);
imshow(redBand);
title('Red band');
subplot(3, 4, 3);
imshow(greenBand);
title('Green band');
subplot(3, 4, 4);
imshow(blueBand);
title('Blue Band');
% Threshold each color band.
redthreshold = 68;
greenThreshold = 70;
blueThreshold = 72;
redMask = (redBand > redthreshold);
greenMask = (greenBand < greenThreshold);
blueMask = (blueBand < blueThreshold);
% Display them.
subplot(3, 4, 6);
imshow(redMask, []);
title('Red Mask');
subplot(3, 4, 7);
imshow(greenMask, []);
title('Green Mask');
subplot(3, 4, 8);
imshow(blueMask, []);
title('Blue Mask');
% Combine the masks to find where all 3 are "true."
redObjectsMask = uint8(redMask & greenMask & blueMask);
subplot(3, 4, 9);
imshow(redObjectsMask, []);
title('Red Objects Mask');
maskedrgbImage = uint8(zeros(size(redObjectsMask))); % Initialize
maskedrgbImage(:,:,1) = rgbImage(:,:,1) .* redObjectsMask;
maskedrgbImage(:,:,2) = rgbImage(:,:,2) .* redObjectsMask;
maskedrgbImage(:,:,3) = rgbImage(:,:,3) .* redObjectsMask;
subplot(3, 4, 10);
imshow(maskedrgbImage);
title('Masked Original Image');
hi. i found above coding from imageAnalyst. my question : 1.) how can i define the red, green, and blue Threshold value?any formula to find the value?for example in my image i want to extract the gold color, and how can i know the exact pixel for gold in RGB colorspace? 2.) can someone explain to me how the coding above works?
tq so much

Best Answer

Use impixelinfo() to have it display the RGB values as you mouse around the image. See updated demo, attached. for the red, green, and blue threshold for the yellow pepper, try these (that I got from the Color Thresholder App):
% Define thresholds for channel 1 (Red) based on histogram settings
channel1Min = 244.000;
channel1Max = 255.000;
% Define thresholds for channel 2 (Green) based on histogram settings
channel2Min = 131.000;
channel2Max = 247.000;
% Define thresholds for channel 3 (Blue) based on histogram settings
channel3Min = 0.000;
channel3Max = 164.000;
Related Question