Python,在numpy数组中加载.csv,返回一个列表

时间:2014-02-06 23:47:39

标签: python dictionary numpy

我想改进此代码,以便最后返回list个“解决方案”:

[bcoords[0, 1, 2, 3], R[0, 1, 2, 3], G[0, 1, 2, 3], B[0, 1, 2, 3]]

代码:

import csv
import numpy as np
import scipy.spatial

points = np.array([(float(X), float(Y), float(Z))
              for R, G, B, X, Y, Z in csv.reader(open('XYZcolorlist_D65.csv'))])
    # load XYZ coordinates of 'points' in a np.array

tri = scipy.spatial.Delaunay(points)
# do the triangulation

indices = tri.simplices
# indices of vertices

vert = points[tri.simplices]
# the vertices for each tetrahedron

targets = np.array([(float(X), float(Y), float(Z))
           for X, Y, Z in csv.reader(open('targets.csv'))])
# load the XYZ target values in a np.array

tetrahedra = tri.find_simplex(targets)
# find which tetrahedron each point belong to

X = tri.transform[tetrahedra,:3]
Y = targets - tri.transform[tetrahedra,3]
b = np.einsum('ijk,ik->ij', X, Y)
bcoords = np.c_[b, 1 - b.sum(axis=1)]
# find the barycentric coordinates of each point

print bcoords

_

代码在两个.csv中加载两个np.array个文件,并使用模块scipy.spatial.Delaunay查找pointtetrahedron的重心坐标。< / p>

XYZcolorlist.csv是点云R,G,B,X,Y,Z

targets.csv是一组目标X,Y,Z

XYZcolorlist.csv:

255,63,127,35.5344302104,21.380721966,20.3661095969
255,95,127,40.2074945517,26.5282949405,22.7094284437
255,127,127,43.6647438365,32.3482625492,23.6181801523
255,159,127,47.1225628354,39.1780944388,22.9366615044
255,223,159,61.7379149646,62.8387601708,32.3936200864
...

targets.csv:

49.72,5,8.64
50.06,5,8.64
50.4,5,8.64
50.74,5,8.64
51.08,5,8.64
51.42,5,8.64
51.76,5,8.64
...

对于targets.csv的每一点,我想得到:

  • 包含vertices

  • 的4 point
  • 与每个顶点关联的4 float(R), float(G), float(B)

  • barycentric coordinates

  • 相关联的4 point

我希望使用numpy

快速快速

代码提供了所有这些,除了4 R, G, B

或者,我可以使用以下代码加载整个文件的数据:

points = np.array([(float(R), float(G), float(B), float(X), float(Y), float(Z))
          for R, G, B, X, Y, Z in csv.reader(open('XYZcolorlist_D65.csv'))])
# load R,G,B,X,Y,Z coordinates of 'points' in a np.array

如何退回清单:

[bcoords[0, 1, 2, 3], R[0, 1, 2, 3], G[0, 1, 2, 3], B[0, 1, 2, 3]]

是否可以构建dict[]

由于

1 个答案:

答案 0 :(得分:1)

我真的使用np.genfromtxt来读取csv文件。 这是一个例子:

import numpy as np
X, Y, Z = np.genfromtxt('targets.csv', delimiter=',', unpack=True)

这比csv容易得多,并且会立即返回numpy.ndarray。