MATLAB: How to export the pixel value of an jpg image to a .txt file

digital image processing

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?

Best Answer

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.