python - 将图像从 Python 传递到 MATLAB 函数

标签 python matlab image-processing python-imaging-library

我正在尝试使用 MATLAB Python 引擎在 Python 中使用 MATLAB 函数。 MATLAB 函数用于处理图像。这是我的代码:

import matlab.engine
import os
from PIL import Image

img_rows, img_cols = 256, 256
img_channels = 1

path0 = r'D:\NEW PICS\non_stressed'
path2 = r'D:\empty2'

listing = os.listdir(path0) 
num_samples=size(listing)
print (num_samples)
eng = matlab.engine.start_matlab()

for file in listing:
    im = Image.open(path0 + '\\' + file)   
    img = im.resize((img_rows,img_cols))
    gray = img.convert('L')

    #gray: This is the image I want to pass from Python to MATLAB
    reg = eng.LBP(gray)   
    reg.save(path2 +'\\' +  file, "JPEG")

但它给了我这个错误:

TypeError: unsupported Python data type: PIL.Image.Image

请帮我解决这个问题。谢谢。

最佳答案

如有关如何 Pass Data to MATLAB from Python 的 MATLAB 文档中所述, 仅支持一定数量的类型。这包括标量数据类型,例如 intfloat 等,以及(部分)dict。此外,listsettuple 会自动转换为 MATLAB 元胞数组。

但是:array.array 和任何 module.type 对象均 受支持。这包括 PIL.Image.Image,就像您的情况一样。在将图像传递给 MATLAB 之前,您必须将图像转换为受支持的数据类型。

对于数组,MATLAB 建议使用其特殊的 MATLAB Array type对于 Python。您可以将 PIL 图像转换为例如uint8 MATLAB 数组

from PIL import Image
import matlab.engine

image = Image.new('RGB', (1024, 1280))
image_mat = matlab.uint8(list(image.getdata()))
image_mat.reshape((image.size[0], image.size[1], 3))

最后的 reshape 命令是必需的,因为 PIL 的 getdata() 函数返回一个扁平化的像素值列表,因此图像的宽度和高度会丢失。现在,您可以在 image_mat 数组上调用任何 MATLAB 函数。

关于python - 将图像从 Python 传递到 MATLAB 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43587226/

相关文章:

image-processing - 在这种情况下,熵是什么意思?

python - 使用 __pycache__ 时 pytest 会隐藏警告

windows - MATLAB:设置非java命令窗口的标题

matlab - 如何将复杂的 csv 文件导入到 Matlab 中的数值向量

python - 使用 OpenCV Python 以与引用图像相同的方向和尺寸转换和显示裁剪图像

python-3.x - Python 中的 3D Dicom 可视化

python - 如何创建项目列表以在 Jinja2 模板页面上多次使用?

python - Tensorboard语法错误: invalid syntax

python - 可逆哈希函数?

c - 错误LNK2001 : unresolved external symbol mexFunction