我想将 DICOM 图像从 int16 转换为 uint8。我已经在 Python 中使用 Z_axis = bytescale(img)
完成了它,但这给出了与在 MATLAB 中使用 im2uint8
不同的结果。在 MATLAB 中,使用 im2uint8
转换为 uint8 后的 DICOM 图像的最小值和最大值分别为 (124, 136)。但是在使用 bytescale
转换后,Python 中的这些值是 (0, 255)。
Python代码:
for person in range(0, len(dirs1)):
if not os.path.exists(os.path.join(directory, dirs1[person])):
Pathnew = os.path.join(directory, dirs1[person])
os.makedirs(Pathnew)
for root, dirs, files in os.walk(os.path.join(path, dirs1[person])):
dcmfiles = [_ for _ in files if _.endswith('.dcm')]
for dcmfile in dcmfiles:
dcm_image = pydicom.read_file(os.path.join(root, dcmfile))
img = dcm_image.pixel_array
Z_axis = bytescale(img)
minVal = Z_axis.min()
maxVal = Z_axis.max()
Matlab代码:
for j = 1 : length(Files2)
img = dicomread([galleryPath Files2(j).name]);
Z_axis = im2uint8(img);
minVal = min(min(Z_axis));
maxVal = max(max(Z_axis));
显示时图像看起来相等,但数值不同。那么,bytescale
和im2uint8
函数是否相等?如果没有,我想要 Python 中的 im2uint8
这样的结果。我应该选择什么样的功能(尤其是对于 DICOM 图像)?
例如,在 MATLAB 中读取 DICOM 文件后:
img = dicomread([galleryPath Files2(j).name]);
img = [ -1024, -1024, 16;
-1024, 8, 11;
17, 5, 8];
但是在Python中,读取后的相同图像是:
dcm_image = pydicom.read_file(os.path.join(root, dcmfile))
img = dcm_image.pixel_array
img = array([[ -1024, -1024, 27],
[ -1024, 27, 26],
[ 24, 26, 23]])
我不知道为什么它们在 MATLAB 和 Python 中不同。在 MATLAB 中应用 im2uint8
后,输出为:
Z_axis = im2uint8(img)
Z_axis =
3×3 uint8 matrix
124 124 128
124 128 128
128 128 128
在 Python 中应用 bytescale
后,输出为:
bytescale(img)
Z_axis =
array([[0, 0, 83],
[0, 83, 83],
[83, 83, 83]], dtype=uint8)
最佳答案
首先,关于读取数据的问题,我建议使用 dcmread
在 Python 中,因为它给了我与 dicomread
相同的精确数据在 MATLAB 中。
其次,在 MATLAB 中当 im2uint8
转换 int16
值,它将缩放它们,假设数据的最小值和最大值分别等于 -32768 和 32767(即 int16
可表示的最小值和最大值)。对于 bytescale
行为等效,我相信你需要相应地设置 cmin
和 cmax
参数(因为否则它们将默认为 data.min()
和data.max()
,分别)。这应该在 Python 中复制 im2uint8
的结果:
Z_axis = bytescale(img.astype(float), cmin=-32768, cmax=32767)
注意:必须首先将数据转换为 float ,以解决 bytescale
中没有正确处理整数运算的明显错误(由 Cris Luengo 提供)。
关于python - 函数 "im2uint8"(在 MATLAB 中)和 "bytescale"(在 Python 中)之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52725553/