在 Matlab 中读取大型结构化文件
在matlab中,我想从一个结构化的、相当大的文件(大小:18+2048*2048字节)中读取,其中第18个字节分配给标题,其余的是像素图像强度。 这里关心的是速度。正如您在下面的代码中看到的,对文件的多次访问大大降低了性能。 您能建议任何更快地从文件中读取这些内容的方法吗?例如,读取缓冲区中的整个内容,我们可以使用“fread”函数从中读取内容。
fid = fopen(fileName, 'r', 'b'); % 'r' readonly and 'b' big endian
a= fread(fid,1,'uint16');
b1= fread(fid,1,'uint32');
b2= fread(fid,1,'uint32');
c1= fread(fid,1,'uint32');
c2= fread(fid,1,'uint32');
img=zeros (...
for i= (b1 + 1) : (b2 + 1)
for j= (c1 + 1) : (c2 + 1)
img(i, j) = fread(fid,1,'uint16');
end
end
In matlab I would like to read from a structured, and rather big, file (size: 18+2048*2048 bytes), where 18 fist bytes are assigned to the header and the rest are pixel image intensities.
The concern here is the speed. As you see in the code below multiple access to the file has considerably slowed down the performance.
Can you suggest any faster way of reading these contents from the file? e.g. reading entire thing in a buffer from which we can read using the "fread" function.
fid = fopen(fileName, 'r', 'b'); % 'r' readonly and 'b' big endian
a= fread(fid,1,'uint16');
b1= fread(fid,1,'uint32');
b2= fread(fid,1,'uint32');
c1= fread(fid,1,'uint32');
c2= fread(fid,1,'uint32');
img=zeros (...
for i= (b1 + 1) : (b2 + 1)
for j= (c1 + 1) : (c2 + 1)
img(i, j) = fread(fid,1,'uint16');
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需计算 b1、b2、c1 和 c2 的总大小 n,并将其传递给单个
fread(fid,n,'uint16')
调用,而不是循环遍历它。然后对输出调用reshape
使其成为二维数组。Just calculate the total size n from b1, b2, c1, and c2, and pass it to a single
fread(fid,n,'uint16')
call instead of looping over it. Then callreshape
on the output to make it a 2-d array.您可以一次性读取图像数据。注意元素的顺序
另一件需要考虑的事情是将数据存储为 uint16 以避免整数到双精度转换:
You can read the image data in one go. Note the order of the elements
One other thing to consider is storing the data as
uint16
to avoid the integer to double conversion:看来你可以简单地一次读取整个图像,如下所示:
It seems that you could simply read the whole image at once like so: