How to save pixel values in an image into text file?

8 views (last 30 days)
I do really hope that you all can help me. I have an image in .jpg format. I want to know the pixel values or intensity values in the image and save the values into text file. But I do not know how to do it. I only know using impixels code but that code only can show the values and can not save the values.

Accepted Answer

Stephen23
Stephen23 on 10 Oct 2014
Edited: Stephen23 on 10 Oct 2014
To save text in a file, try fprintf, or one of the higher-level text-file IO functions .
Note you can navigate MATLAB's help very easily using the "Contents" on the left hand side of the help browser. There you can find related functions, examples and explanations of all functions in MATLAB. If you spend some time looking around the "Contents", you will discover the sections related to image operations, file operations, and of course basic MATLAB concepts and practices.

More Answers (1)

Image Analyst
Image Analyst on 10 Oct 2014
Try this:
rgbImage = imread('peppers.png');
[rows, columns, numberOfColorChannels] = size(rgbImage)
fid = fopen('deleteme.txt', 'wt');
for col = 1 : columns
for row = 1 : rows
fprintf(fid, '%d, %d = (%d, %d, %d)\n', ...
row, col, ...
rgbImage(row, col, 1),...
rgbImage(row, col, 2),...
rgbImage(row, col, 3));
end
end
And this snippet might come in handy to ask your user for the name of the output file
% Get the name of the file that the user wants to save.
% Note, if you're saving an image you can use imsave() instead of uiputfile().
startingFolder = userpath
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
  6 Comments
Stephen23
Stephen23 on 25 May 2020
@Image Analyst: it looks like the userpath was cleared at some point. Try calling
userpath('reset')
and check it again.
Image Analyst
Image Analyst on 25 May 2020
Edited: Image Analyst on 25 May 2020
That restored it. I see in my startup.m file I did have that, but it was commented out because it takes several seconds to execute, but that means I must have had it cleared somehow before, though I don't remember how or why. Thanks.
By the way, fizaAhalim, attached is a demo of mine where you can write to a CSV file the x, y, red, green, and blue values of the image you specify.

Sign in to comment.

Categories

Find more on Images 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!