在Python3.x中调用Matlab .m文件后,如何解决“ TypeError”和“ ValueError”?

时间:2018-10-30 07:27:56

标签: python matlab

我想在Python中调用Matlab .m文件和函数,但是由于Matlab和Python之间的数据类型不同,因此发生了TypeError: unsupported Python data type: numpy.ndarray错误。

作为下面代码中的示例,VoxelSizeUnification是一个Matlab函数,我想在Python中调用它,其输入来自Python数据类型:

import matlab.engine
eng = matlab.engine.start_matlab()

xyzSpacing = [dcm_image.SliceThickness, dcm_image.PixelSpacing[1], dcm_image.PixelSpacing[0]]
xyzNewSpacing = [1.25, 1.25, 1.25]
eng.VoxelSizeUnification(volume_image, xyzNewSpacing, xyzSpacing)  # TypeError: unsupported Python data type: numpy.ndarray

volume_image is {ndarray} and includes images as: volume_image[number of slices in 3rd dimenson = 133, rows=512, columns=512].
xyzNewSpacing and xyzSpacing are <class 'list'> with size of (1 x 3)

此外,我使用link1搜索,但是我不想保存文件然后加载它们。同样在link2中,mlab应该与python> = 2.7一起使用,而我的Python是3.6.6和Matlab 2017b。

我还尝试过matlab.double,并使用示例没有任何错误来测试上述代码:

xyzNewSpacing = matlab.double([1.25, 1.25, 1.25])
xyzSpacing = matlab.double([1.5, 1.5, 1.5])
vol = matlab.double([[[1, 2, 1], [3, 1, 5], [2, 1, 2]],
                     [[2, 3, 1], [1, 2, 3], [2, 1, 3]],
                     [[4, 2, 1], [2, 3, 1], [3, 2, 1]]])
ret = eng.VoxelSizeUnification(vol, xyzNewSpacing, xyzSpacing)

但是对于volume_image(它是3D图像阵列),我收到有关以下内容的错误:ValueError: initializer must be a rectangular nested sequence

Python:

xyzNewSpacing = matlab.double([1.25, 1.25, 1.25])
xyzSpacing = matlab.double([1.5, 1.5, 1.5])
d = matlab.double(volume_image) # ValueError: initializer must be a rectangular nested sequence
ret = eng.VoxelSizeUnification(d, xyzSpacing, xyzNewSpacing)

Matlab:

function outputSize = VoxelSizeUnification(d, xyzSpacing, xyzNewSpacing)
         outputSize = [ceil((d(1)*xyzSpacing(1))/xyzNewSpacing(1))...
                      ceil((d(2)*xyzSpacing(2))/xyzNewSpacing(2))...
                       ceil((d(3)*xyzSpacing(3))/xyzNewSpacing(3))];
end

ValueError: initializer must be a rectangular nested sequence的原因是什么?谢谢。

2 个答案:

答案 0 :(得分:1)

该错误是由于datatypes引起的,并且使用volume_image = volume_image.tolist()已解决了该错误。但是,这花费了大量的运行时间。因此,如果每个人都有一个好主意,请分享。

答案 1 :(得分:0)

您尝试过使用mlabwrap吗?

检查此链接-可能会有帮助

Calling MATLAB .m-files and functions in Python script