Alberto Acri asked . 2023-08-24

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}];

impixelinfo , values , numbers , image analysis , image processing , cell , cell array

Expert Answer

Prashant Kumar answered . 2024-05-17 19:24:59

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

Frequently Asked Questions

MATLAB offers tools for real-time AI applications, including Simulink for modeling and simulation. It can be used for developing algorithms and control systems for autonomous vehicles, robots, and other real-time AI systems.

MATLAB Online™ provides access to MATLAB® from your web browser. With MATLAB Online, your files are stored on MATLAB Drive™ and are available wherever you go. MATLAB Drive Connector synchronizes your files between your computers and MATLAB Online, providing offline access and eliminating the need to manually upload or download files. You can also run your files from the convenience of your smartphone or tablet by connecting to MathWorks® Cloud through the MATLAB Mobile™ app.

Yes, MATLAB provides tools and frameworks for deep learning, including the Deep Learning Toolbox. You can use MATLAB for tasks like building and training neural networks, image classification, and natural language processing.

MATLAB and Python are both popular choices for AI development. MATLAB is known for its ease of use in mathematical computations and its extensive toolbox for AI and machine learning. Python, on the other hand, has a vast ecosystem of libraries like TensorFlow and PyTorch. The choice depends on your preferences and project requirements.

You can find support, discussion forums, and a community of MATLAB users on the MATLAB website, Matlansolutions forums, and other AI-related online communities. Remember that MATLAB's capabilities in AI and machine learning continue to evolve, so staying updated with the latest features and resources is essential for effective AI development using MATLAB.

Without any hesitation the answer to this question is NO. The service we offer is 100% legal, legitimate and won't make you a cheater. Read and discover exactly what an essay writing service is and how when used correctly, is a valuable teaching aid and no more akin to cheating than a tutor's 'model essay' or the many published essay guides available from your local book shop. You should use the work as a reference and should not hand over the exact copy of it.

Matlabsolutions.com provides guaranteed satisfaction with a commitment to complete the work within time. Combined with our meticulous work ethics and extensive domain experience, We are the ideal partner for all your homework/assignment needs. We pledge to provide 24*7 support to dissolve all your academic doubts. We are composed of 300+ esteemed Matlab and other experts who have been empanelled after extensive research and quality check.

Matlabsolutions.com provides undivided attention to each Matlab assignment order with a methodical approach to solution. Our network span is not restricted to US, UK and Australia rather extends to countries like Singapore, Canada and UAE. Our Matlab assignment help services include Image Processing Assignments, Electrical Engineering Assignments, Matlab homework help, Matlab Research Paper help, Matlab Simulink help. Get your work done at the best price in industry.