MATLAB Answers

how to export the pixel value of an jpg image to a .txt file?

18 views (last 30 days)
Farrukh
Farrukh on 2 Nov 2012
how to export the pixel value of an jpg image to a .txt file? and after that how import pixel value from .txt to matlab so that original image can be displayed?

Accepted Answer

Jan
Jan on 2 Nov 2012
Edited: Jan on 2 Nov 2012
You forgot to mention, if you have imported the JPG already. And you did not specify the format of the txt file. While writing the pixel values is trivial, the re-creation of the image requires the dimensions also.
img = imread('YourImage.jpg');
fid = fopen('YourImage.txt', 'w');
if fid == -1, error('Cannot open file'); end
fprintf(fid, '%d %d %d ', size(img)); % Assuming it is an RGB image
fprintf(fid, '%g ', img(:));
fclose(fid);
The re-import:
fid = fopen('YourImage.txt', 'r');
if fid == -1, error('Cannot open file'); end
ImgSize = fscanf(fid, '%d %d %d ', 3);
ImgData = fscanf(fid, '%g ', Inf);
Img = reshape(ImgData, ImgSize);
fclose(fid);
The file will be shorter, if you convert the floating point values to integers before writing:
ImgInt = round(Img * 255);
and a corresponding back-transformation after the reading.
BTW. Are you really sure that this is useful? imread seems to be more convenient.
  1 Comment
Farrukh
Farrukh on 5 Nov 2012
the above stated solution is working but the size of the text file(.txt) was very large above then the size of image but when i was copied the pixel value directly in the text file (Note pad file) from matlab command window the size is much less as compared to that process.......so is there is any way to get the less size of text file..........

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!