使用MatLab数据在Python中创建.PNG图像

时间:2014-09-24 19:51:09

标签: python matlab scipy

实际上我试图用Python创建.png图像。数据来自Matlab文件。 在这里我的代码。当我跑步时我有错误:

追踪(最近一次通话):   File" readFromMatLab.py",第20行,in     matriz [x] [y] [z] = data [x] [y] [z] IndexError:列表索引超出范围

Matlab文件的数据是512x512x200双数组。

> {'__version__': '1.0', 'St3D': array([[[ -4.98510788e-02, 
> -4.98139346e-02,  -4.97636073e-02, ...,
>           -5.19862428e-02,  -5.20095813e-02,  -5.20122990e-02],
>         [ -4.98249255e-02,  -4.97792210e-02,  -4.97507640e-02, ...,
>           -5.19832396e-02,  -5.19884452e-02,  -5.20089354e-02],
>         [ -4.98121755e-02,  -4.97751679e-02,  -4.97488529e-02, ...,
>           -5.19605824e-02,  -5.19734534e-02,  -5.20023879e-02],
>         ...,
>        [[  9.10799464e-05,   1.75287655e-04,   2.26928715e-04, ...,
>            1.10619951e-04,   1.04038395e-04,   7.44506576e-05],
>         [  6.29097917e-05,   1.20765020e-04,   1.91577341e-04, ...,
>            8.24078623e-05,   8.96774520e-05,   7.44268856e-05],
>         [  4.14273859e-05,   7.96562916e-05,   1.20801256e-04, ...,
>            9.05750282e-05,   8.13201896e-05,   6.77554603e-05],
>         ..., 
>         [  1.72297366e-04,   1.68849830e-04,   2.21771692e-04, ...,
>            2.30046391e-04,   2.51247428e-04,   2.58021432e-04],
>         [  2.06350049e-04,   1.92126121e-04,   2.58923928e-04, ...,
>            2.48977658e-04,   2.78131275e-04,   2.76242136e-04],
>         [  2.42915268e-04,   2.47607632e-04,   2.89283796e-04, ...,
>            2.58819021e-04,   2.76203977e-04,   2.82977241e-04]]]), '__header__': 'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Fri
> Sep 19 17:03:17 2014', '__globals__': []}


#!/usr/bin/python
# -*- coding: utf-8 -*-
import pprint
import scipy.io
import numpy
from scipy import misc
from PIL import Image

# import file into a dictionary
fMatLab = scipy.io.loadmat('St3D', mat_dtype = True, squeeze_me = True, struct_as_record=False)

# read in the structure
data = fMatLab['St3D']

matriz = [[[0 for col in range(data.shape[0])] for row in range(data.shape[1])] for x in range(data.shape[2])]

for x in range(0,data.shape[0]):
    for y in range(0,data.shape[1]):
        for z in range(0,data.shape[2]):
            matriz[x][y][z] = data[x][y][z]

for i in range(len(matriz)):
    #im = numpy.random.random_integers(0, 255, 512*512).reshape((512, 512))
    misc.imsave('transect_%s.png' % i, matriz[i])

from glob import glob
filelist = glob('transect*.png')
filelist.sort()

1 个答案:

答案 0 :(得分:1)

我认为您试图将misc.imsave应用于数据的某个维度的每个切片。但是,代码的效率非常低,尤其是从matriz =matriz[x][y][z] =。您已经将矩阵存储为变量data中的numpy数组,因此不需要列表推导或循环。如果你想在一个维度上循环一个numpy数组的切片,例如,第三个维度,要应用一个函数,只需执行以下操作:

for i in xrange(data.shape[2]):
    some_function(data[:, :, i])

修改 在您的情况下,这将转换为

data = fMatLab['St3D']
for i in xrange(data.shape[2]):
    misc.imsave('transect_%s.png' % i, data[:, :, i])

而且,作为一个快速的最后一点,最后三行不应该缩进。