How to plot mat file in python

I have a file myfile.mat exported from octave, it contains three matrices X, Y, U all of them have same size and I want to plot surface U where X, Y are the x and y components of surface U. I can do it in octave with the following code:

surf(X,Y,U)

But I want to do it in python also. I am using pythonxy and for plotting the data in python first of all I import the data with spyder GUI interactively after I saw the matrices in variable explorer in spyder I implement the following codes

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.plot_surface(X, Y, U, rstride=8, cstride=8, alpha=0.3)

But I see just a blank figure window. Here is the data myfile.mat

How to plot mat file in python

asked Dec 26, 2013 at 16:31

2

I suspect that you are forgetting to include a call to plt.show() at the end. This function has no analog in MATLAB/Octave, but is absolutely required in matplotlib. Also, please be aware that plt.show() doesn't seem to work properly inside of loops in some Python environments, so if you are trying to generate multiple images at once (for example, generating 10 different figures inside of a "for" loop) that may be a hidden source of problems for you as well. Furthermore, you need to define a colormap using the cmap=cm.<whatever> option in the call to the ax.plot_surface() method. A list of all the colormaps that you may use can be found here. And finally, your strides are too large for the tiny little data file that you included. I've appended example code and the resulting image below. I left out setting alpha=0.3 because it is unnecessary for this data (there is nothing in front of or behind anything else) but you may put it back in if you like; the code will still work.

How to plot mat file in python

import scipy.io
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

data = scipy.io.loadmat('myfile.mat')
X = data['X']
Y = data['Y']
U = data['U']

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, U, rstride=1, cstride=1, cmap=cm.jet)
fig.colorbar(surf)

plt.show()

answered Dec 27, 2013 at 15:44

stachyrastachyra

4,3334 gold badges19 silver badges31 bronze badges

1

Not the answer you're looking for? Browse other questions tagged python matplotlib plot octave or ask your own question.

How to plot mat file in python

Matlab is a really popular platform for scientific computing in the academia. I’ve used it my throughout my engineering degree and chances are, you will come across .mat files for datasets released by the universities.

This is a brief post which explains how to load these files using python, the most popular language for machine learning today.

The data

I wanted to build a classifier for detecting cars of different models and makes and so the Stanford Cars Dataset appeared to be a great starting point. Coming from the academia, the annotations for the dataset was in the .mat format. You can get the file used in this post here.

Loading .mat files

Scipy is a really popular python library used for scientific computing and quite naturally, they have a method which lets you read in .mat files. Reading them in is definitely the easy part. You can get it done in one line of code:

from scipy.io import loadmat
annots = loadmat('cars_train_annos.mat')

Well, it’s really that simple. But let’s go on and actually try to get the data we need out of this dictionary.

Formatting the data

The loadmat method returns a more familiar data structure, a python dictionary. If we peek into the keys, we’ll see how at home we feel now compared to dealing with a .mat file:

annots.keys()
> dict_keys(['__header__', '__version__', '__globals__', 'annotations'])

Looking at the documentation for this dataset, we’ll get to learn what this is really made of. The README.txt gives us the following information:

This file gives documentation for the cars 196 dataset.
(http://ai.stanford.edu/~jkrause/cars/car_dataset.html)
— — — — — — — — — — — — — — — — — — — —
Metadata/Annotations
— — — — — — — — — — — — — — — — — — — —
Descriptions of the files are as follows:
-cars_meta.mat:
Contains a cell array of class names, one for each class.
-cars_train_annos.mat:
Contains the variable ‘annotations’, which is a struct array of length
num_images and where each element has the fields:
bbox_x1: Min x-value of the bounding box, in pixels
bbox_x2: Max x-value of the bounding box, in pixels
bbox_y1: Min y-value of the bounding box, in pixels
bbox_y2: Max y-value of the bounding box, in pixels
class: Integral id of the class the image belongs to.
fname: Filename of the image within the folder of images.
-cars_test_annos.mat:
Same format as ‘cars_train_annos.mat’, except the class is not provided.
— — — — — — — — — — — — — — — — — — — —
Submission file format
— — — — — — — — — — — — — — — — — — — —
Files for submission should be .txt files with the class prediction for
image M on line M. Note that image M corresponds to the Mth annotation in
the provided annotation file. An example of a file in this format is
train_perfect_preds.txt
Included in the devkit are a script for evaluating training accuracy,
eval_train.m. Usage is:
(in MATLAB)
>> [accuracy, confusion_matrix] = eval_train(‘train_perfect_preds.txt’)
If your training predictions work with this function then your testing
predictions should be good to go for the evaluation server, assuming
that they’re in the same format as your training predictions.

Our interest is in the 'annotations' variable, as it contains our class labels and bounding boxes. It’s a struct, a data type very familiar to folks coming from a strongly typed language like a flavour of C or java.

A little digging into the object gives us some interesting things to work with:

type(annots[‘annotations’]),annots[‘annotations’].shape
>(numpy.ndarray, (1, 8144))
type(annots['annotations'][0][0]),annots['annotations'][0][0].shape
>(numpy.void, ())

The annotations are stored in a numpy.ndarray format, however the data type for the items inside this array is numpy.void and numpy doesn’t really seem to know the shape of them.

The documentation page for the loadmat method tells us how it loads matlab structs into numpy structured arrays.You can access the members of the structs using the keys:

annots[‘annotations’][0][0][‘bbox_x1’], annots[‘annotations’][0][0][‘fname’]> (array([[39]], dtype=uint8), array(['00001.jpg'], dtype='<U9'))

So now that we know how to access the members of the struct, we can iterate through all of them and store them in a list:

[item.flat[0] for item in annots[‘annotations’][0][0]]> [39, 116, 569, 375, 14, '00001.jpg']

Here, we can use the flat method to squeeze the value out of the array.

Hello Pandas

Now that we know how to deal with matlab files in python, let’s convert it into a pandas data frame. We can do so easily using a list of lists:

data = [[row.flat[0] for row in line] for line in annots[‘annotations’][0]]columns = [‘bbox_x1’, ‘bbox_y1’, ‘bbox_x2’, ‘bbox_y2’, ‘class’, ‘fname’]
df_train = pd.DataFrame(data, columns=columns)

How to plot mat file in python

Finally, familiar territory!

The code for this post can be found here.

How do I visualize a .MAT file in Python?

By default, Python is not capable of reading . mat files. We need to import a library that knows how to handle the file format..
Install scipy. Similar to how we use the CSV module to work with . ... .
Import the scipy. io. ... .
Parse the . ... .
Use Pandas dataframes to work with the data..

How do I visualize a .MAT file?

mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .

Can we use mat file in Python?

Matlab 7.3 and greater Beginning at release 7.3 of Matlab, mat files are actually saved using the HDF5 format by default (except if you use the -vX flag at save time, see in Matlab). These files can be read in Python using, for instance, the PyTables or h5py package.

How do I load a .MAT dataset in Python?

Just do as follows:.
Install the package: pip install pymatreader..
Import the relevant function of this package: from pymatreader import read_mat..
Use the function to read the matlab struct: data = read_mat('matlab_struct. mat').
use data. keys() to locate where the data is actually stored..