Find RGB color code in an image

3 ビュー (過去 30 日間)
Chathurika Sandamali
Chathurika Sandamali 2021 年 8 月 14 日
回答済み: Image Analyst 2021 年 8 月 14 日
I want to find the centrod point's RGB color code of the attached image. I tried following code. But its RGB code it wrong and that code is always displayed of any image I have. I attched output of this code and original image.
What is the reason that. Please help me to resolve the problem.
clc;
clear all;
close all;
[fname path] = uigetfile('*.*', 'Enter an Image');
fname = strcat(path, fname);
im = imread(fname);
im = imresize(im, [300 NaN]);
figure, imshow(im)
bw = im2bw(im, graythresh(getimage));
figure, imshow(bw);
title('');
bw2 = imfill(bw,'holes');
L = bwlabel(bw2);
s = regionprops(L, 'centroid');
centroids = cat(1, s.Centroid);
%Display original image and superimpose centroids.
hold(imgca,'on')
X = plot(imgca,centroids(:,1), centroids(:,2), 'r*');
% plot(imgca,centroids(:,1), centroids(:,2), 'r*')
yData = round(X.YData);
xData = round(X.XData);
;
R = im(:,:,1);
G = im(:,:,2);
B = im(:,:,3);
c = [R(xData,yData) G(xData,yData) B(xData,yData)];
fprintf('Color = %d\n', c);

採用された回答

Simon Chan
Simon Chan 2021 年 8 月 14 日
Modify this line by swapping xData & yData
c = [R(yData,xData) G(yData,xData) B(yData,xData)];
  3 件のコメント
Chathurika Sandamali
Chathurika Sandamali 2021 年 8 月 14 日
@Image Analyst Really I want to find the average RGB color code all over the stick. but I could not do it. Therefore I tried this. If you can help, it is lot of help me for my studies.

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2021 年 8 月 14 日
@Chathurika Sandamali, try the code below to get the average color over the whole stick, which is better than just getting it at the centroid like you originally asked for. If it helps you, can you click the "Vote" icon or accept the answer?
% Demo by Image Analyst, August, 2021.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
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 = 'IMG_5063.JPG';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~isfile(fullFileName)
% 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
fullFileName = fullFileNameOnSearchPath;
end
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display the image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
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';
%--------------------------------------------------------------------------------------------------------
% Segment (mask) the image.
[mask, maskedRGBImage] = createMask(rgbImage);
% Fill holes in the mask.
mask = imfill(mask, 'holes');
% Take largest blob only.
mask = bwareafilt(mask, 1);
% Display the mask image.
subplot(2, 2, 2);
imshow(mask, []);
axis('on', 'image');
caption = sprintf('Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Update masked image with new mask
% 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, maskedRGBImage, cast(mask, 'like', maskedRGBImage));
% Display the masked image.
subplot(2, 2, 3);
imshow(maskedRGBImage);
axis('on', 'image');
caption = sprintf('Masked Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Split the image into red, green, and blue channels.
[redChannel, greenChannel, blueChannel] = imsplit(maskedRGBImage);
% Get the mean R, G, and B values in the masked region
meanR = mean(redChannel(mask))
meanG = mean(greenChannel(mask))
meanB = mean(blueChannel(mask))
caption = sprintf('Mean Red Value of stick = %.2f.\nMean Green Value of stick = %.2f.\nMean Blue Value of stick = %.2f.\n',...
meanR, meanG, meanB);
fprintf('%s\n', caption);
caption = sprintf('Masked Image : Mean (Red, Green, Blue) Values = (%.2f, %.2f, %.2f.)',...
meanR, meanG, meanB);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
%====================================================================================
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-Aug-2021
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.000;
channel1Max = 1.000;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.127;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.456;
channel3Max = 1.000;
% 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;
end

Community Treasure Hunt

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

Start Hunting!

Translated by