# How to convert .mat file struct into pytorch Tensors

**URL:** <https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094>\
**Category:** vision\
**Created:** [February 24, 2019, 11:50am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094 "2019-02-24T11:50:12Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![mamoona\_nisar](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mamoona_nisar/32/11284_2.png) [@mamoona\_nisar](https://discuss.pytorch.org/u/mamoona_nisar)\
**Post date:** [February 24, 2019, 11:50am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/1 "2019-02-24T11:50:12Z")

</div>

Hi ,I have 3064 images dataset into single .mat (matlab) file.  
The file has structures format.  
How can I access the structure using pytorch.I have Loaded in Python the .mat file but not sure how to access data from it.  
Following are the items in cjdata structure  
cjdata.image  
cjdata.id  
cjdata.tumorborder

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [February 24, 2019, 12:38pm UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/2 "2019-02-24T12:38:08Z")

</div>

I guess you’ve opened the file using `scipy.io`?  
If so, you should get a `dict` with all the members and can just load these arrays as numpy arrays.  
Once you have the numpy data, you can transform them to `torch.Tensors` using `torch.from_numpy()`.  
Have a look at some examples from the [scipy docs](https://docs.scipy.org/doc/scipy/reference/tutorial/io.html) on how to load the data.

---

<div class="post-metadata">

**Author:** ![mamoona\_nisar](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mamoona_nisar/32/11284_2.png) [@mamoona\_nisar](https://discuss.pytorch.org/u/mamoona_nisar)\
**Post date:** [February 24, 2019, 3:10pm UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/3 "2019-02-24T15:10:51Z")

</div>

Thanks ,your reply is helpful .Before moving to numpy- then tensor.  
I need little help more please.  
this is how is combined all .mat structure in one mat.See so you can get idea for my problem.

```auto
% % Making single mat file for all images detail
% for i=1:3064                     
% fname = strcat('data/figshareBrainTumorDataPublic/',num2str(i),'.mat')
% load(fname)
% label(i) = cjdata.label;
% PID(i) = {cjdata.PID};
% if (size(cjdata.image,1) ~= 512) 
% image(i,:,:) = imresize(cjdata.image, [512, 512]);
% tumorMask(i,:,:) = imresize(cjdata.tumorMask, [512, 512]);
% else
% image(i,:,:) = cjdata.image;
% tumorMask(i,:,:) = cjdata.tumorMask;
% end
% clear cjdata fname
% end
% save('data/figshareBrainTumorDataPublicNewSingle/data.mat', 'label', 'PID', 'image', 'tumorMask');

```

The code in Python so far is :

```auto
import scipy.io as io
fname='./data.mat'
data= io.loadmat(fname)
fname=data['label','PID','image','tumorBorder','tumorMask'] 

```

‘image’ has all 3064 images.How can I access one image from it :fname=data[‘image’] or selective images.like 4 image.Thankyou for helping me  
Please suggest best way to make the data ready for pytorch CNN.I m beginner at this. 🙂

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [February 24, 2019, 4:56pm UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/4 "2019-02-24T16:56:15Z")

</div>

Is `data['image']` returning a numpy array?  
If so, you could just slice it using e.g. `data['image'][:4]`, if you want to get the first 4 images.  
You could try to write your custom `Dataset`, load all data in ` __init__ `, and get a single sample in ` __getitem__ `. Here is some dummy example:

```python
class MyDataset(Dataset):
    def __init__ (self, mat_path):
        data = io.loadmat(mat_path)
        self.images = torch.from_numpy(data['images'])
        self.targets = torch.from_numpy(data['tumorMask'])

    def __getitem__ (self, index):
        x = self.images[index]
        y = self.targets[index]
        return x, y

    def __len__ (self):
        return len(self.images)

```

Also, have a look at the [Data loading tutorial](https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#dataset-class) to see how the `Dataset` and `DataLoader` play together.

---

<div class="post-metadata">

**Author:** ![mamoona\_nisar](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mamoona_nisar/32/11284_2.png) [@mamoona\_nisar](https://discuss.pytorch.org/u/mamoona_nisar)\
**Post date:** [February 24, 2019, 7:03pm UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/5 "2019-02-24T19:03:12Z")

</div>

![image](https://discuss.pytorch.org/uploads/default/original/2X/8/89ec090288aedcf91a9050f352a3201e8ed76f99.png)

This is what i m getting .

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [February 24, 2019, 8:41pm UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/6 "2019-02-24T20:41:41Z")

</div>

Is `imshow` showing something?  
Based on the variable explorer it looks like your first images are all zero.  
Also, the images seem to be single channel images. Is this correct?

---

<div class="post-metadata">

**Author:** ![mamoona\_nisar](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mamoona_nisar/32/11284_2.png) [@mamoona\_nisar](https://discuss.pytorch.org/u/mamoona_nisar)\
**Post date:** [February 25, 2019, 5:49am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/7 "2019-02-25T05:49:40Z")

</div>

Imshow is not showing anything.yes you are right.Your command data[‘image’][:4] return (4,512,512) and does not displays images.  
But `fname=data['image']`  
returns long arrays.  
 ![image](https://discuss.pytorch.org/uploads/default/original/2X/8/83b2cb56c5457400b8447c462de9a75883aa1b7d.png)

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [February 25, 2019, 7:10am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/8 "2019-02-25T07:10:52Z")

</div>

Are you expecting this image format? In a previous post you’ve mentioned `data['image']` should contain 3064 images. Now your `fname` seems to have 1207 images. Maybe the data is being stored/loaded in the wrong format.

---

<div class="post-metadata">

**Author:** ![mamoona\_nisar](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mamoona_nisar/32/11284_2.png) [@mamoona\_nisar](https://discuss.pytorch.org/u/mamoona_nisar)\
**Post date:** [February 25, 2019, 7:13am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/9 "2019-02-25T07:13:31Z")

</div>

I don’t know why the it has 1207 images.I have stored through loop with i value 3064.  
Why this happening I don’t know.This is how i stored in one mat file:

```auto
% % Making single mat file for all images detail
for i=1:3064
    fname = strcat('data/figshareBrainTumorDataPublic/',num2str(i),'.mat')
    load(fname)
    label(i) = cjdata.label;
    PID(i) = {cjdata.PID};
    image(i,:,:) = cjdata.image;
     tumorBorder(i,:) = cjdata.tumorBorder;
     tumorMask(i,:,:) = cjdata.tumorMask;
end
% save('data/figshareBrainTumorDataPublicNewSingle/data.mat', 'label', 'PID', 'image', 'tumorMask');
 save('data/figshareBrainTumorDataPublicNewSingle/data.mat', 'label', 'PID', 'image', 'tumorBorder', 'tumorMask');

```

---

<div class="post-metadata">

**Author:** ![mamoona\_nisar](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mamoona_nisar/32/11284_2.png) [@mamoona\_nisar](https://discuss.pytorch.org/u/mamoona_nisar)\
**Post date:** [February 25, 2019, 7:22am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/10 "2019-02-25T07:22:08Z")

</div>

By the way I have the other method running byside.saved 3064 images as png from mat files.I have saved 3 labeled folders (images stored as PNG) .But found RuntimeError: Found 0 files in subfolders.

 ![image](https://discuss.pytorch.org/uploads/default/original/2X/2/2d59b6fb364af62d57b4ac8f590e9550bc1437bd.png) .  
"each subfolders in "train “have png images.”

---

<div class="post-metadata">

**Author:** ![saba](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/saba/32/19439_2.png) [@saba](https://discuss.pytorch.org/u/saba)\
**Post date:** [January 16, 2020, 8:44am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/11 "2020-01-16T08:44:30Z")

</div>

Hi Ptrblck

I want to save data as mat file in the pytorch which command is the right one. I can load mat file but now I need to save my tensor or numpy array as mat file.  
I used this one \>\>\> scipy.io.savemat(‘images1.mat’, images1.numpy())  
images1 are my input patches. but it dose not work.

I appreciate your reply.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [January 17, 2020, 1:09am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/12 "2020-01-17T01:09:21Z")

</div>

The command looks alright.  
What kind of error do you get?

---

<div class="post-metadata">

**Author:** ![saba](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/saba/32/19439_2.png) [@saba](https://discuss.pytorch.org/u/saba)\
**Post date:** [January 17, 2020, 2:06am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/13 "2020-01-17T02:06:42Z")

</div>

Thank you I solve it I should have used

io.savemat(os.path.join(root\_dirDurringTraining11+’/’,“images”+str(i)+".mat"), {“images11”: images1.numpy()})

---

<div class="post-metadata">

**Author:** ![hahaha\_lts](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hahaha_lts/32/27025_2.png) [@hahaha\_lts](https://discuss.pytorch.org/u/hahaha_lts)\
**Post date:** [July 23, 2020, 9:06am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/14 "2020-07-23T09:06:01Z")

</div>

Hi, I got sing channel images from ‘.mat’. And I write my custom Dataset, but got some **errors.RuntimeError: output with shape [1, 21, 21] doesn’t match the broadcast shape [3, 21, 21]**  
 ![error](https://discuss.pytorch.org/uploads/default/original/3X/1/f/1f0ae95bc8935bb35712c39426085f7cd6ae372d.png)  
my images array shape(1596, 21, 21)

---

<div class="post-metadata">

**Author:** ![hahaha\_lts](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hahaha_lts/32/27025_2.png) [@hahaha\_lts](https://discuss.pytorch.org/u/hahaha_lts)\
**Post date:** [July 23, 2020, 9:10am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/15 "2020-07-23T09:10:48Z")

</div>

@ptrblck sorry if I disturb you

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [July 23, 2020, 10:00am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/16 "2020-07-23T10:00:26Z")

</div>

I guess `transforms.Normalize` raises this error, since you are using a single-channel tensor, while `Normalize` uses 3 values for the `mean` and `stddev`.  
If you are dealing with grayscale images, you could pass `tuples` containing a single element to `Normalize`:

```python
transforms.Normalize((0.5,), (0.5,))

```

---

<div class="post-metadata">

**Author:** ![hahaha\_lts](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hahaha_lts/32/27025_2.png) [@hahaha\_lts](https://discuss.pytorch.org/u/hahaha_lts)\
**Post date:** [July 23, 2020, 10:13am UTC](https://discuss.pytorch.org/t/how-to-convert-mat-file-struct-into-pytorch-tensors/38094/17 "2020-07-23T10:13:45Z")

</div>

thank you sir！ sovled it
