save the RGB numbers of an image inside a cell

Illustration
Alberto Acri - 2023-08-24T13:50:34+00:00
Question: save the RGB numbers of an image inside a cell

Hi. I would like to save the RGB numbers of an image (see RGB_value) inside a cell (see matrix) that has the same size as the image and in the same determined position.   For example: in the code below I have taken the values X=71 and Y=35 to which correspond RGB_value = [244 244 244]. I should save this RGB_value inside a 'matrix' cell at position X=71 and Y=35.   I should then apply the same argument for all other RGB_values for X=1:col_imageArray and Y=1:row_imageArray.   At the moment I was only able to determine RGB_value of one pixel but I can't insert this value inside the cell at the desired position.   imageArray = importdata("ssg.jpg"); figure() imshow(imageArray) impixelinfo row_imageArray = height(imageArray); col_imageArray = width(imageArray); matrix = {}; X = 71; Y = 35; RED = imageArray(Y,X,1); GREEN = imageArray(Y,X,2); BLUE = imageArray(Y,X,3); RGB_value = [RED, GREEN, BLUE]; matrix = [matrix,{RGB_value}];

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

I know you said you want a cell but I think you really don't want a slow, inefficient, memory hogging cell array. I think you should use just a regular, fast and efficient double matrix. Frankly I'm not even sure why you think you want a matrix of all the pixel locations and their RGB values. Unless it's your homework which seems probable. Anyway, here is a full, extremely well commented demo to do that:

 

 

% Take an RGB Image and write all the pixel info to a csv file in the form [R, G, B, X, Y].
% It will have as many rows as pixels in the image, and have those 5 columns.
% Initialization steps.
clc;    % Clear the command window.
close all;  % Close all figures (except those of imtool.)
clear;  % Erase all existing variables. Or clearvars if you want.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;

%----------------------------------------------------------------------------------------------------------
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = pwd; % or 'C:\wherever';
if ~isfolder(startingFolder)
    % If that folder doesn't exist, just start in the current folder.
    startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select an RGB image file');
if baseFileName == 0
    % User clicked the Cancel button.
    return;
end
fullFileName = fullfile(folder, baseFileName)

%----------------------------------------------------------------------------------------------------------
% Read in the image.
rgbImage = imread(fullFileName);
% Display the image.
imshow(rgbImage);
% Put up statusbar to let you mouse around over it and see r, g, b, and (x, y)
impixelinfo();
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0.2, 0.2, 0.8, 0.8]);
drawnow; % Force immediate screen repaint.
% Get x and y for all pixels.
[rows, columns, numberOfColorChannels] = size(rgbImage)
if numberOfColorChannels == 1
    % This is not an RGB image.
    promptMessage = sprintf('This is not an RGB image\nDo you want to Continue processing as grayscale, \nMake RGB,\nor Quit processing?');
    titleBarCaption = 'Continue?';
    buttonText = questdlg(promptMessage, titleBarCaption, 'Grayscale', 'Make RGB', 'Quit', 'Continue');
    if contains(buttonText, 'Quit')
        return;
    elseif contains(buttonText, 'RGB')
        % Convert to RGB.
        rgbImage = cat(3, rgbImage, rgbImage, rgbImage);
        [rows, columns, numberOfColorChannels] = size(rgbImage);
    else
        % Leave as grayscale.
    end	
end

%----------------------------------------------------------------------------------------------------------
% Get all the x and y values.
[x, y] = meshgrid(1:columns, 1:rows);

%----------------------------------------------------------------------------------------------------------
% Extract the individual red, green, and blue color channels.
% Need to cast to double or else x and y will be clipped to 255 when we concatenate them.
if numberOfColorChannels == 1
    % Leave as gray scale.
    % Get array listing [r, g, b, x, y].  Using (:) will turn all the 2-D arrays into column vectors.
    output = [rgbImage(:), x(:), y(:)];
else
    redChannel = double(rgbImage(:, :, 1));
    greenChannel = double(rgbImage(:, :, 2));
    blueChannel = double(rgbImage(:, :, 3));
    % Get array listing [r, g, b, x, y].  Using (:) will turn all the 2-D arrays into column vectors.
    output = [redChannel(:), greenChannel(:), blueChannel(:), x(:), y(:)];
end

%----------------------------------------------------------------------------------------------------------
% Get the output filename - same as input file name but with .csv extension.
[folder, baseFileNameNoExtension, extension] = fileparts(fullFileName);
baseFileName = [baseFileNameNoExtension, '.txt'];
% folder = pwd; % Change to current folder.
outputFileName = fullfile(folder, baseFileName);
% Write output to CSV file.
message = sprintf('Please wait...\n    Writing data to text file:\n        %s', outputFileName);
fprintf('%s\n', message);
% For the output file, convert it to a table so we can have column headers.
output = array2table(output, 'VariableNames', {'R', 'G', 'B', 'X', 'Y'});
% Display the first 10 rows of the table in the command window.
head(output)
% Write the table to disk.
writetable(output, outputFileName);

%----------------------------------------------------------------------------------------------------------
% Let user know we're done.
fprintf('Done creating output file!\n    Wrote data to CSV file:\n        %s\n', outputFileName);
% Open up
promptMessage = sprintf('Done!\n\nWrote data to CSV file:\n%s\n\nDo you want me to it now?', outputFileName);
titleBarCaption = 'Open?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Yes - open it', 'No, do not open it', 'Yes - open it');
if contains(buttonText, 'No,')
    return;
end
if ispc
    winopen(outputFileName);
end

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!