how to do model prediction using python in matlab
12 views (last 30 days)
Show older comments
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:
out.write(data_in_json)
and this is in matlab (I'm using R2019b)
system('test_model.py'); %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\test_model.py", line 1, in <module>
import keras
ImportError: No module named keras
2 Comments
Answers (1)
Peter O
on 22 Jul 2021
So it looks like it's launching into Python fine. A couple things to try:
- 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.
- 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?
- Try calling the python file through the system call as 'python test_model.py'. This should be no different than calling the file, but stranger things have happened.
3 Comments
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!