How would you detect a certain color square in an image?

2 views (last 30 days)
How would you detect the red square in the left middle section of the image?

Answers (1)

Image Analyst
Image Analyst on 8 Jun 2017
I'd get the index of the red square in the indexed image, and then mask it.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
%===============================================================================
% Read in a indexed demo image.
folder = pwd;
baseFileName = 'squaresImage3.gif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
[indexedImage, storedColorMap] = imread(fullFileName);
% Get the dimensions of the image. numberOfColorChannels should be = 3.
[rows, columns, numberOfColorChannels] = size(indexedImage);
% Display the original color image.
subplot(2, 2, 1);
imshow(indexedImage, storedColorMap);
axis on;
title('Original Color Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0, 1, 1]);
% Get the index in the red region.
indexOfRed = indexedImage(200, 200)
% Create a mask
mask = indexedImage == indexOfRed;
% Display the mask image.
subplot(2, 2, 2);
imshow(mask);
axis on;
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
% Mask the image using bsxfun() function
maskedIndexedImage = bsxfun(@times, indexedImage, cast(mask, 'like', indexedImage));
% Display the mask image.
subplot(2, 2, 3);
imshow(maskedIndexedImage, storedColorMap);
axis on;
title('Masked Image', 'FontSize', fontSize, 'Interpreter', 'None');

Categories

Find more on Convert Image Type 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!