首页 > 解决方案 > 使用 Matlab 引擎将 Numpy ndarray 传递到 Matlab 函数时数据损坏

问题描述

我在 Matlab 中有一个函数,我想调用我在 Python 中作为 2d ndarray 加载的灰度图像。为此,我选择使用 Matlab Engine for Python。

按照这个答案,我选择使用 Scipy 的 savemat() 函数,然后我将我的 ndarray 打包到字典中,如这个答案所示。然后在 Matlab 端,我使用 fopen() 读取了这个文件。

在这个过程中的某个地方,图像第一行的前 50 个单元格被损坏了。

Python代码:

self.eng = matlab.engine.start_matlab()
savemat(out_file_python, {'image_data': image})
FILTERED_IMAGE = self.eng.SARBM3D_Python_Helper(out_file_matlab, L, width, height)

Matlab代码:

    function IMG_FILTERED = SARBM3D_Python_Helper(path, L, width, height)
    %SARBM3D_filter Takes an image path, loads the image and applies
    %    SARBM3D filter.
    %   Detailed explanation goes here
    [fp, msg] = fopen(path,'rb'); 
    assert(fp>=3,msg)
    IMG = fread(fp,[width height],'float')'; 
    fclose(fp);

    tic;
    IMG_FILTERED = SARBM3D_v10(IMG,L);
    toc,

    end

这是可行的,图像由 Python 保存,然后由 Matlab 加载。问题是Matlab读取的图像的第一行的前50个单元格中充满了垃圾号:

5.97010568981204e-07    167969504   2.04630902945563e+23    1.94329244039050e-19    7.14394306433430e+31    4.68937780150775e+27    7.54651052656269e+31    3.86486210083297e+30    7.21283771132713e+22    1.85015188025444e+28    6.34833865368594e+28    2.39079247928242e+29    6.48021303284452e-10    0.000698821619153023    1.73404984593617e-07    6.48018139148832e-10    1.72892204528396e-41    0   0   0   0   0   0   0   0   0   0   0   0   0   210767872   1.96181785005474e-44    4.65006882401547e-40    8.40779078594890e-45    1.12103877145985e-44    9.80908925027372e-45    0   7.00649232162409e-45    1.12103877145985e-44    4.03573957725547e-43    4.03573957725547e-43    1.40129846432482e-45    1.40129846432482e-44    1.06455071979708e+24    2.63295721825752e+20    3.49595940879755e-41    0   9.80908925027372e-45    4.64917199299831e-40

然后在这50个垃圾条目之后,图像数据是正常的。

我的理论是,在序列化和反序列化之间发生了某个问题,并且某些元数据被作为图像的一部分读取。我需要在 Matlab 中打开“image_data”字典吗?

标签: pythonmatlabnumpy

解决方案


尝试将文件作为对象加载mat到 Matlab 而不是fopen. 它也将保持您原来的阵列形状。

fp = load(path); 

推荐阅读