How to save pixel values in an image into text file?
Show older comments
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
More Answers (1)
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
krishna kotha
on 25 May 2020
what is userpath here
Image Analyst
on 25 May 2020
I think it used to be a built-in variable, but it seems it no longer is. Just replace it with pwd or whatever hard-coded string representing a folder that you want.
startingFolder = pwd;
startingFolder = 'D:/my images'; % Wherever you want...
Stephen23
on 25 May 2020
Image Analyst
on 25 May 2020
>> userpath
ans =
0×0 empty char array
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
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.
Categories
Find more on Environment and Settings 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!