Skip to main content
 首页 » 编程设计

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

2024年10月01日8powertoolsteam

我正在尝试使用 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 文档中所述, 仅支持一定数量的类型。这包括标量数据类型,例如 int、float 等,以及(部分)dict。此外,list、set 和 tuple 会自动转换为 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 函数。