MATLAB: Replacing RGB value for image segmentation

Image Processing Toolboximage segmentationmaskingMATLABpixelrgbsubstitution

Hi!
Is it possible, for certain RGB values ​​of pixels in an image, to make modifications like this below?
For example, for pixels with values ​​in ranges: Red between 170 – 120, Green 150 – 120 and Blue between 70 – 50, I would not like to modify. But for pixels that are not in this range, I'd like to make them in black color.
Thanks.

Best Answer

Sure. Just make a mask and apply it:
rgbImage = imread('peppers.png');
subplot(2, 1, 1);
imshow(rgbImage);
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Create a mask for each channel and use it to zero out the image.
mask = ~(redChannel >= 120 & redChannel <= 170);
redChannel(mask) = 0;
mask = ~(greenChannel >= 120 & greenChannel <= 150);
greenChannel(mask) = 0;
mask = ~(blueChannel >= 50 & blueChannel <= 70);
blueChannel(mask) = 0;
% Recombine separate color channels into a single, true color RGB image.
rgbImage2 = cat(3, redChannel, greenChannel, blueChannel);
subplot(2, 1, 2);
imshow(rgbImage2);
0001 Screenshot.png