how to do model prediction using python in matlab

12 views (last 30 days)
this is the python code, and it works so well in python
import keras
from keras.models import load_model
from keras.preprocessing import image
import json
import numpy as np
filepath = 'model2.h5'
test_img = 'falling14145853.png'
model = keras.models.load_model(filepath)
img = image.load_img(test_img, target_size=(150, 150))
x = image.img_to_array(img)
x = np.expand_dims(x, axis = 0)
images = np.vstack([x])
classes = model.predict(images, batch_size = 10)
_mapping = ["falling", "sitting", "standing"]
a = np.concatenate(classes, axis=None).astype(int).tolist()
idx = np.argmax(a[0])
prediction = _mapping[idx]
response_json = {"Prediction" : prediction}
data_in_json = json.dumps(response_json)
with open("prediction.json", "w") as out:
and this is in matlab (I'm using R2019b)
system(''); %doing prediction
this is the matlab output and i've tried to run pyhton to make a capture using cv and works so well in matlab but when I tried to run python code which contain of keras, its showing this error
>> bismillahbisaaaa
Traceback (most recent call last):
File "E:\angie\", line 1, in <module>
import keras
ImportError: No module named keras
Eugenia Angela Salsabillah
Edited: Eugenia Angela Salsabillah on 22 Jul 2021
Thank you for your suggestion, I would like to try to follow that documentation first. Also I'm using python 3.7 already. And I have tried to running cv2 using python in matlab and it works so well without adding py. like in the documentation

Sign in to comment.

Answers (1)

Peter O
Peter O on 22 Jul 2021
So it looks like it's launching into Python fine. A couple things to try:
  1. Standard Python or Anaconda? Sometimes Anaconda doesn't play so well. Make sure you're launching matlab from the Anaconda prompt if you go this route, and sometimes the python libraries that depend on dll's will still have some trouble. If OpenCV is playing nicely in a python call through MATLAB, then chances are you're OK there.
  2. Is it a case of environments? Is the activated environment missing keras? Is it a module import problem? Does numpy or another library import without issue if you do that first?
  3. Try calling the python file through the system call as 'python'. This should be no different than calling the file, but stranger things have happened.
Eugenia Angela Salsabillah
Thank you so much. I'm so excited because the problem is solved by adding 'python' and just it.
So, the code becomes

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by