How to convert image to binary text file?
13 ビュー (過去 30 日間)
古いコメントを表示
Hello, I have a 512x640 16 bit image. It is in uint16 format. It doesn't have color information (RGB). I want convert each pixel's value to binary and write it to a text file. I've tried some codes but it didn't work. How can i do it? Lets assume my image is 4 bit and the .txt file contains should seem like this:
0010
1100
0100
.
.
1000

0 件のコメント
回答 (1 件)
DGM
2023 年 11 月 25 日
編集済み: DGM
2023 年 11 月 25 日
The error is probably because you don't have write permissions to whatever directory you're trying to write to. You'll have to figure out why that is.
I assume you want to write the output as 16 bit, and that you weren't actually suggesting to convert it to 4-bit.
% a uint16 array
A = im2uint16(imread('cameraman.tif'));
% you should probably explicitly specify the field width.
% otherwise, the width will vary depending on the maximum values in A.
binStr = dec2bin(A,16);
% if whatever reads the file can handle variable-length fields,
% then you could save filesize by omitting the field width specification.
%binStr = dec2bin(A);
% write one word per line
% the expression length given to fprintf() needs to correspond
% to the actual field width, since it's not necessarily 16 characters!
% if the two mismatch, binary words will be split across lines
% and the result will be a jumbled mess.
fname = 'test_binary.txt';
fid = fopen(fname,'w');
expr = [repmat('%c',[1 size(binStr,2)]) '\n'];
fprintf(fid,expr,binStr.');
fclose(fid);
I'm not sure why you're storing image data this way, but bear in mind that you're going to create giant files. Even writing raw uncompressed binary data is much more compact.
% this is 8x as large as an uncompressed PGM
% and 18x as large as a lossless PNG
S = dir(fname); S.bytes
imwrite(A,'test.pgm')
S = dir('test.pgm'); S.bytes
imwrite(A,'test.png')
S = dir('test.png'); S.bytes
2 件のコメント
DGM
2023 年 11 月 26 日
編集済み: DGM
2023 年 11 月 26 日
FWIW, formats like PGM are very simple binary data with a short header. There really isn't any decoding to do. Depending on the effort-memory tradeoff, you might consider using PGM or even a headerless raw binary file. It would be significantly smaller than text, if that's of any concern (assuming you have the option of changing how the embedded code accepts inputs).
参考
カテゴリ
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!