将array转成list比较简单,如下:

#array to list
import numpy as np  #array模块,但其只支持一维数组,不支持多维数组,也没有各种运算函数。
#matrix=[0 for i in range(4)]  #这样定义的数组时list object,可以拿list当数组用
matrix_array=np.random.randint(0,3,(2,3))
#其他定义
#array = np.empty((5, 4), dtype=int)    #可以用于预先申请内存
matrix_list = matrix_array.tolist()

将list转换成数组。

由于list中可以存放不同类型的元素,因此在转换成数组时,为了保证转换不出错,要检查类型是否一致,有数字且有字符的list转成array时会变成字符数组。

import numpy as np
# define list
array = np.asarray(list)
#the second method
array = np.array(list, dtype = int)

list对象的常用方法有:

list=[1,2,3,4,5]   #list的定义以[]方式,tuple的定义以()方式
list.insert(1, 'content')    #在指定位置插入元素
list.pop()    #将最后一位的元素删除
list.pop(i)    #删除指定位置的元素,i从0开始
list[-1]    #下标访问

下面介绍一个快速的将list转换成array的函数,代码来自 TSN_ECCV2016,如下:

def fast_list2arr(data, offset=None, dtype=None):
    """
    Convert a list of numpy arrays with the same size to a large numpy array.
    This is way more efficient than directly using numpy.array()
    See
        https://github.com/obspy/obspy/wiki/Known-Python-Issues
    :param data: [numpy.array]
    :param offset: array to be subtracted from the each array.
    :param dtype: data type
    :return: numpy.array
    """
    num = len(data)
    out_data = np.empty((num,)+data[0].shape, dtype=dtype if dtype else data[0].dtype)
    for i in xrange(num):
        out_data[i] = data[i] - offset if offset else data[i]
    return out_data

 该方法中每个元素都是array,但是整个对象是array list,要转换成array of array 才能送入caffe网络进行预测。原理是先申请空间再逐一复制array list中的每个元素。

使用的时候会比较方便,如下图片的处理:

frame = fast_list2arr([cv2.resize(x, frame_size) for x in frame])

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐