python - 使用 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”字典吗?
解决方案
尝试将文件作为对象加载mat
到 Matlab 而不是fopen
. 它也将保持您原来的阵列形状。
fp = load(path);
推荐阅读
- c++ - Visual Studio 的输出未显示浮点数和双精度数的所有有效数字与 C++ 代码
- flutter - 如何在 Flutter 中编写能够获取图像作为输入的卡片小部件?
- amazon-web-services - AWS 子网的重叠
- c#-3.0 - NSubstitute 测试仅在构建服务器中失败
- java - 由于某种原因,我的 inflate 没有显示 xml 文件,这是为什么?
- java - 为什么要避免在接口类中使用对调用者敏感的方法名称?
- mongodb - AWS DocumentDB BulkUpdate 长时间运行
- python - 为什么 pystary 菜单会引发这么多错误?
- spring - 推土机客户转换器在没有 XML 配置的情况下无法工作
- algorithm - 硬币有限的硬币变化算法 - 方案