How to pass an image from Python to Matlab?

I want to pass an image from my Python script to Matlab.
Following is my Python script:
import matlab.engine
from PIL import Image
import os
eng = matlab.engine.start_matlab()
image = Image.open('Tile_X0_Y14336.jpg')
image_mat = matlab.uint8(list(image.getdata()))
passimage = image_mat.reshape((image.size[0], image.size[1], 3))
eng.image_display(passimage)
This is my Matlab Script:
clc;
clear all;
close all;
function y= image_display(a)
a=imread(y)
figure;
imshow(a);
end
However, I am getting an error saying 'TypeError: None cannot be passed to MATLAB' in output window.
Can anyone please help me to pass an image from my python script to Matlab script?

Answers (1)

Hi Rucha,
The "getdata" method produces a flat list of pixel values, which loses the original 2D structure of the image. Attempting to restore this structure using "reshape" can be problematic if the image is not in the expected format or if the reshaping does not match the original dimensions.
I tried the following code, and it worked for me. You might want to give it a try:
import matlab.engine
from PIL import Image
import numpy as np
eng = matlab.engine.start_matlab()
image = Image.open('image.jpg')
image_np = np.array(image)
image_mat = matlab.uint8(image_np.tolist())
eng.image_display(image_mat, nargout=0)
I hope it resolves your issue!!

Asked:

on 30 May 2019

Answered:

on 11 Dec 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!