Image to Text conversion
35 次查看(过去 30 天)
显示 更早的评论
I try to convert image of size 512 x 512 into text file of hexadecimal values using this code
a= imread('im16_1a.png');
I=rgb2gray(a);
imgTrans = I';
% iD conversion
img1D = I(:);
% Decimal to Hex value conversion
imgHex = dec2hex(img1D);
% New txt file creation
fid = fopen('im16_1.txt', 'wt');
% Hex value write to the txt file
fprintf(fid, '%x\n', imgHex);
% Close the txt file
fclose(fid)
the text file must contain (512 x 512) 262144 values but it shows (512 x 512 x 3) 786432 values, pls help, what to do.. ??
5 个评论
回答(1 个)
Geoff Hayes
2014-5-5
编辑:Geoff Hayes
2014-5-5
The code is converting the uint8 integer array, Img1D, to the hexadecimal equivalent, stored as characters:
imgHex = dec2hex(img1D);
imgHex has the same number of rows as Img1D but two columns. The code then writes out the data to the text file with
fprintf(fid, '%x\n', imgHex);
But does the above not mean that the we are writing in hex the already hex'ed data? If I do the same with an image (once converted to a 1D array) of 215760 pixels, then the imgHex is 215760x2. I then write to the file (as above) and when I try to read it in again line-by-line (using getl), the result is a 431520x2 array which is twice the size of the original. In fact, just writing out one line to the file (with the above fprintf) results in two lines in the output file.
I think what you really want to be doing is to write out the hex of the uint8 data instead:
fprintf(fid, '%x\n', img1D);
Please try out the above line to see if that helps.
EDIT:
Try the following to demonstrate what is happening with the writing of the hex data in hex:
fprintf('%x\n','00')
The '00' is two character equivalent of the conversion from uint8 (to hex) of the integer 0. The fprintf will then convert each character in this string to its hex equivalent. The hex equivalent for each character is '30'. And so the output is
30
30
2 个评论
dipak
2016-2-26
编辑:Geoff Hayes
2016-2-27
img = rgb2gray(img);
imshow(img);
dlmwrite('image.txt',img,'delimiter','\t');
Walter Roberson
2016-2-27
To match the user's requirements you would need
dlmwrite('image.txt', img(:), 'precision', '%02x');
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Convert Image Type 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!