Matlab读取图像数据并写入TXT

我最近在做嵌入式图像处理,我的任务是:首先要把一幅图像读入matlab,获取每个像素点的灰度值,然后分别在TXT文件中以二进制、十进制和十六进制的数值显示出来。

在matlab中使用imread函数读入一幅图像,得到由图像灰度构成的uint8类型的数值矩阵,然后用fopen、fclose进行文件的读写操作,用printf函数将数值打印到TXT文档中,话不多说,上代码。

由于图像数据太大,所以先写一个测试程序,这是以十进制形式输出

%% 测试程序1
close all;clear;clc;
mat=uint8(magic(4))
fid=fopen('F:\TXT测试文件\decimal.txt','wt');  %在1-decimal.txt中写入十进制数据
COUNT=fprintf(fid,'%d\n',mat');
fclose(fid);

因为matlab中图像数据读取时是按列读取和存储,而做图像处理时要按行处理,所以这里我们输出是需要将矩阵mat转置。

下面是十六进制形式输出

%% 测试程序2
close all;clear;clc;
mat=uint8(magic(4))
format hex
fid=fopen('F:\TXT测试文件\hex.txt','wt');  %在1-decimal.txt中写入十六进制数据
COUNT=fprintf(fid,'%x\n',mat');
fclose(fid);

运行结果如下

 

但是,同样的方法输出二进制数据时却出现了问题。我在这里卡了很久,不怕大家笑话,我在这块在CSDN上找帖子学习,前后花了两周左右,总算初步学懂了几个数据I/O的函数,比如fopen、fprintf、dlmwrite,围绕这个问题还初步了解有cell、fwrite、csvwrite、xslwrite、magic、save等等。有时间再好好总结一下这次的经验,先把作业完成再说。

我想将这些数据转换成只有01的八位二进制代码,并在TXT文本中显示它们,也像上面一样一个数据一个换行。

 最常用的办法是用matlab中的dec2bin函数,查看它的帮助文件。

>> help dec2bin
dec2bin Convert decimal integer to its binary representation
    dec2bin(D) returns the binary representation of D as a character vector.
    D must be a non-negative integer. If D is greater than flintmax, 
    dec2bin might not return an exact representation of D.
 
    dec2bin(D,N) produces a binary representation with at least
    N bits.
 
    Example
       dec2bin(23) returns '10111'

dec2bin(D)将矩阵D转换成二进制字符串显示,dec2bin(D,N)中N是转换后的位数。

%% 测试程序3
close all;clear;clc;
mat=uint8(magic(4))
mat1=dec2bin(mat',8)
dlmwrite('F:\TXT测试文件\binary.txt',mat1,'delimiter','','newline','pc');

 

测试成功后用真实的图像数据试一试

clc;clear;close all;
I=imread('50.jpg');                 %读入八位十进制灰度值0-255
INFO=imfinfo('50.jpg');
R=rgb2gray(I);
%figure,imshow(I),figure,imshow(R);

%% 化成1-0黑白图像
m=graythresh(R);
BW1=im2bw(R,m);
figure,
subplot(131),imshow(BW1),title('灰度图像分为0和1');
n=graythresh(I);
BW2=im2bw(I,n);
subplot(132),imshow(BW2),title('原图分为0和1');
subplot(133),imshow(I),title('原图')

%% 以十进制字符串显示
fid=fopen('F:\360MoveData\Users\asus\Desktop\嵌入式实验\图像处理\1-decimal.txt','wt');   %在1-binary.txt中写入十进制数据
COUNT=fprintf(fid,'%d\n',R','int');%十进制数据存入TXT
sta=fclose(fid);

%% 以二进制字符串显示
B=dec2bin(R');
dlmwrite('F:\360MoveData\Users\asus\Desktop\嵌入式实验\图像处理\1-binary.txt',B,'delimiter','','newline','pc');

%% 以十六进制字符串显示
format hex         %只影响数据输出格式,不影响计算和存储
fid=fopen('F:\360MoveData\Users\asus\Desktop\嵌入式实验\图像处理\1-hex.txt','wt');      %在1-hex.txt中写入十六进制数据
COUNT2=fprintf(fid,'%x\n',R');
fclose(fid);

二进制字符显示那段代码因为数据量比较大的缘故,运行时间较长,具体时间因电脑性能而异。耐心等待一会,生成三个TXT文件,大小分别是1-binary.txt(12.5MB)、1-decimal.txt(6.00MB)、1-hex.txt(4.94MB)。打开后检查,符合要求,成功。

贴一下sprintf、fprintf的帮助

sprintf Write formatted data to string or character vector
    STR = sprintf(FORMAT, A, ...) applies FORMAT to all elements of
    array A and any additional array arguments in column order, and returns
    the results as STR. FORMAT can be a character vector or a string
    scalar. The data type of STR is the same as the data type of FORMAT.
 
    [STR, ERRMSG] = sprintf(FORMAT, A, ...) returns an error message when
    the operation is unsuccessful.  Otherwise, ERRMSG is empty.
 
    sprintf is the same as FPRINTF except that it returns the data in a 
    MATLAB variable rather than writing to a file.
 
    FORMAT describes the format of the output fields, and can include 
    combinations of the following:
 
       * Conversion specifications, which include a % character, a
         conversion character (such as d, i, o, u, x, f, e, g, c, or s),
         and optional flags, width, and precision fields.  For more
         details, type "doc sprintf" at the command prompt.
 
       * Literal text to print.
 
       * Escape characters, including:
             \b     Backspace            ''   Single quotation mark
             \f     Form feed            %%   Percent character
             \n     New line             \\   Backslash
             \r     Carriage return      \xN  Hexadecimal number N
             \t     Horizontal tab       \N   Octal number N%
         where \n is a line termination character on all platforms.
 
    Notes:
 
    If you apply an integer or text conversion to a numeric value that
    contains a decimal, MATLAB overrides the specified conversion, and
    uses %e to express the value in exponential notation.
 
    Numeric conversions print only the real component of complex numbers.
 
    Examples
       sprintf('%0.5g',(1+sqrt(5))/2)       % 1.618
       sprintf('%0.5g',1/eps)               % 4.5036e+15       
       sprintf('%15.5f',1/eps)              % 4503599627370496.00000
       sprintf('%d',round(pi))              % 3
       sprintf('%s','hello')                % hello
       sprintf('The array is %dx%d.',2,3)   % The array is 2x3.
 
    See also fprintf, sscanf, num2str, int2str, char, string, compose.

    sprintf 的参考页
    名为 sprintf 的其他函数
fprintf Write formatted data to text file.
    fprintf(FID, FORMAT, A, ...) applies the FORMAT to all elements of 
    array A and any additional array arguments in column order, and writes
    the data to a text file.  FID is an integer file identifier.  Obtain 
    FID from FOPEN, or set it to 1 (for standard output, the screen) or 2
    (standard error). fprintf uses the encoding scheme specified in the
    call to FOPEN.
 
    fprintf(FORMAT, A, ...) formats data and displays the results on the
    screen.
 
    COUNT = fprintf(...) returns the number of bytes that fprintf writes.
 
    FORMAT is a string that describes the format of the output fields, and
    can include combinations of the following:
 
       * Conversion specifications, which include a % character, a
         conversion character (such as d, i, o, u, x, f, e, g, c, or s),
         and optional flags, width, and precision fields.  For more
         details, type "doc fprintf" at the command prompt.
 
       * Literal text to print.
 
       * Escape characters, including:
             \b     Backspace            ''   Single quotation mark
             \f     Form feed            %%   Percent character
             \n     New line             \\   Backslash
             \r     Carriage return      \xN  Hexadecimal number N
             \t     Horizontal tab       \N   Octal number N
         For most cases, \n is sufficient for a single line break.
         However, if you are creating a file for use with Microsoft
         Notepad, specify a combination of \r\n to move to a new line.
 
    Notes:
 
    If you apply an integer or string conversion to a numeric value that
    contains a fraction, MATLAB overrides the specified conversion, and
    uses %e.
 
    Numeric conversions print only the real component of complex numbers.
 
    Example: Create a text file called exp.txt containing a short table of
    the exponential function.
 
        x = 0:.1:1;
        y = [x; exp(x)];
        fid = fopen('exp.txt','w');
        fprintf(fid,'%6.2f  %12.8f\n',y);
        fclose(fid);
 
    Examine the contents of exp.txt:
 
        type exp.txt
 
    MATLAB returns:
           0.00    1.00000000
           0.10    1.10517092
                ...
           1.00    2.71828183
 
    See also fopen, fclose, fscanf, fread, fwrite, sprintf, disp.

    fprintf 的参考页
    名为 fprintf 的其他函数

dlmwrite参见博客1

思考:如何把二维矩阵变成一维,有直接变换的函数吗?

  • 13
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值