简体   繁体   English

读取二进制文件只打印零

[英]Reading binary file prints only zeros

I am trying to read a 3D image binary file and display a slice of the 3D image in python.The format is int16 with big endian.我正在尝试读取 3D 图像二进制文件并在 python 中显示 3D 图像的切片。格式为 int16,大端。 The file extension is .rec .文件扩展名为.rec I have the following piece of code:我有以下代码:

struct_fmt = '>h' # big-endian,signed int16
struct_len = struct.calcsize(struct_fmt)
struct_unpack = struct.Struct(struct_fmt).unpack_from

results = []
with open('test.rec', "rb") as f:
    while True:
        data = f.read(struct_len)
        if not data: break
        s = struct_unpack(data)
        results.append(s)

img3d = np.array(results)
img3d = img3d.reshape(401,401,326)
np.save('output.npy',img3d)
image = np.load('output.npy')
fig,ax=plt.subplots()
output_slice=image[:,190,:]
ax.imshow(output_slice,cmap='gray')
ax.axis('off')
plt.show()

But I get all the voxel values as 0. And the image is black.但我将所有体素值都设为 0。而且图像是黑色的。 What am I missing?我错过了什么?

I found the solution.我找到了解决方案。 In matplotlib, the convention is (z,x,y), so that means the smaller resolution comes first.在 matplotlib 中,约定是 (z,x,y),这意味着较小的分辨率优先。 So it means there are 326 projections of 401x401 2D images.所以这意味着有 326 个 401x401 2D 图像的投影。 So actually the voxels values were getting misplaced.所以实际上体素值错位了。 so i had a distorted image.所以我有一个扭曲的形象。 Also plotting a histogram of voxel values helped a lot.绘制体素值的直方图也很有帮助。 Just used plt.hist(img_arry.ravel(),bins=50) to plot a histogram.刚刚使用 plt.hist(img_arry.ravel(),bins=50) 到 plot 一个直方图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM