我最近在做嵌入式图像处理,我的任务是:首先要把一幅图像读入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 representationdec2bin(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 leastN bits.Exampledec2bin(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 vectorSTR = sprintf(FORMAT, A, ...) applies FORMAT to all elements ofarray A and any additional array arguments in column order, and returnsthe results as STR. FORMAT can be a character vector or a stringscalar. The data type of STR is the same as the data type of FORMAT.[STR, ERRMSG] = sprintf(FORMAT, A, ...) returns an error message whenthe 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, aconversion character (such as d, i, o, u, x, f, e, g, c, or s),and optional flags, width, and precision fields.  For moredetails, 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 thatcontains a decimal, MATLAB overrides the specified conversion, anduses %e to express the value in exponential notation.Numeric conversions print only the real component of complex numbers.Examplessprintf('%0.5g',(1+sqrt(5))/2)       % 1.618sprintf('%0.5g',1/eps)               % 4.5036e+15       sprintf('%15.5f',1/eps)              % 4503599627370496.00000sprintf('%d',round(pi))              % 3sprintf('%s','hello')                % hellosprintf('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 writesthe 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 thecall to FOPEN.fprintf(FORMAT, A, ...) formats data and displays the results on thescreen.COUNT = fprintf(...) returns the number of bytes that fprintf writes.FORMAT is a string that describes the format of the output fields, andcan include combinations of the following:* Conversion specifications, which include a % character, aconversion character (such as d, i, o, u, x, f, e, g, c, or s),and optional flags, width, and precision fields.  For moredetails, 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 NFor most cases, \n is sufficient for a single line break.However, if you are creating a file for use with MicrosoftNotepad, 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 thatcontains a fraction, MATLAB overrides the specified conversion, anduses %e.Numeric conversions print only the real component of complex numbers.Example: Create a text file called exp.txt containing a short table ofthe 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.txtMATLAB returns:0.00    1.000000000.10    1.10517092...1.00    2.71828183See also fopen, fclose, fscanf, fread, fwrite, sprintf, disp.fprintf 的参考页名为 fprintf 的其他函数

dlmwrite参见博客1

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

Matlab读取图像数据并写入TXT相关推荐

  1. matlab读取二进制文件字符串,matlab读取内容为二进制的TXT文件

    本方法同样适合读取十六进制和二进制以外的其他进制文件, txt使用一个最简单的命令就可以读取 textread 这是一个十分有用,简便的函数(对于fopen fscanf而言) 读取二进制txt文件: ...

  2. Matlab读取Eprime数据(txt文档)

    Eprime程序跑完后生成的数据是edat格式,matlab不能直接读取,如果手动merge和export我觉得不太方便,尤其当数据是陆续收集而不是一下子就收好的时候.而且如果两个edat文件的被试或 ...

  3. matlab 读取照片imread,利用matlab读取图像

    怎样用matlab读取20张图片并依次展示出来 指定路径下 单个文件夹data中所有图像 P = '.\data\';% 图像文件夹路径 img_path_list = dir(strcat(P,'* ...

  4. 怎么用matlab读一张图像,利用matlab读取图像

    怎样用matlab读取20张图片并依次展示出来 指定路径下 单个文件夹data中所有图像 P = '.\data\';% 图像文件夹路径 img_path_list = dir(strcat(P,'* ...

  5. Python从数据库读取大量数据批量写入文件的方法

    今天小编就为大家分享一篇Python从数据库读取大量数据批量写入文件的方法,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 使用机器学习训练数据时,如果数据量较大可能我们不能够一次性将 ...

  6. Matlab读取二进制数据文件

    第一步:函数fopen打开文件 fid=fopen('文件名',读取方式) fid:句柄值 小于0表示打开失败:大于0表示打开成功 文件名:字符串,使用单引号(本文例子'savedata.dat') ...

  7. python批量读取文件内容_Python从数据库读取大量数据批量写入文件的方法

    使用机器学习训练数据时,如果数据量较大可能我们不能够一次性将数据加载进内存,这时我们需要将数据进行预处理,分批次加载进内存. 下面是代码作用是将数据从数据库读取出来分批次写入txt文本文件,方便我们做 ...

  8. IDL和MATLAB读取grib数据

    IDL读取grib数据 (1)      需要IDL8.1以上版本 (2)      代码如下:        (3)      读取的数据结果在ENVI中查看如下: 可以看到在山东半岛的角上的值为0 ...

  9. python读取数据库数据、并保存为docx_Python从数据库读取大量数据批量写入文件的方法...

    Python从数据库读取大量数据批量写入文件的方法 使用机器学习训练数据时,如果数据量较大可能我们不能够一次性将数据加载进内存,这时我们需要将数据进行预处理,分批次加载进内存. 下面是代码作用是将数据 ...

  10. Kinect V1读取图像数据(For Windows)

    Kinect V1读取图像数据(For Windows) 这篇博客 Kinect V1介绍 数据读取的基本流程 运行代码和注释 结尾 这篇博客  刚好有一台现成的Kinect V1相机,所以就拿过来学 ...

最新文章

  1. [JS][dfs]题解 | #迷宫问题#
  2. 2016年10月CPU天梯图
  3. C和指针之字符串编程练习8实现char *my_strnchr(char const *str, int ch, int which)
  4. jqgrid mvc_将JQGrid与Spring MVC和Gson集成
  5. 马斯克为何不惜激怒众“韭菜”?
  6. 计算机系统注册表文件格式,WIN7系统中,如何在注册表中修改系统时间格式?...
  7. Mac系统下使用cd命令无法进入目录
  8. java小数的数据类型_Java的基本数据类型
  9. Java获取文本文件编码
  10. 如何实现异地远程登录计算机,两台异地电脑怎么实现远程控制
  11. Vuex的使用(九)——actions的其他用法
  12. 盘点HTML转义字符集合
  13. semantic ui中文文档_求你别再用swagger了,给你推荐几个在线文档生成神器
  14. 超全植物UE4素材素材网站整理
  15. python登录并关注公众号_python爬虫之微信公众号关注度排行榜
  16. 一段的冷笑话已经很直白的说明了三方的关系
  17. 虚拟服务器影视站设置,虚拟主机可以开电影网站吗
  18. linux禁用usb存储不禁用鼠标,禁用USB 不影响USB鼠标键盘 | 吴文辉博客
  19. win10卸载git_打造 Win10 终极开发环境
  20. 7-5 井字棋 (15分)

热门文章

  1. 【论文泛读05】基于Conv-LSTM的短期交通流预测
  2. 项目实战-电商(网上书城)
  3. moea切比雪夫_基于分解的多目标进化优化MOEA/D之切比雪夫方法代码
  4. 华为ensp 多区域OSPF配置
  5. astah java版本_astah community
  6. 二维数组与指针(详解)
  7. c语言水文水资源,长江中游水文网
  8. Struts1 面试题目总结
  9. C/C++实现atoll函数
  10. python 圆周率_圆周率 python