adrienlucca.net
adrienlucca.net

Reputation: 687

Python, load and list a .csv in a numpy array

I am loading a .csv file with this code:

import csv
import numpy as np
import scipy.spatial

points = np.array([((int(R), int(G), int(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  

print points 

And that works fine.

However, if I add this further line, where I am trying to compute a Delaunay triangulation with scipy: http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html

tri = scipy.spatial.Delaunay(points[1, 2, 3])
# do the triangulation

I get this error message:

Traceback (most recent call last):
  File "C:\Users\gary\Documents\EPSON STUDIES\delaunay.py", line 15, in <module>
    tri = scipy.spatial.Delaunay(points[1, 2, 3])
IndexError: too many indices

Obviously the syntax scipy.spatial.Delaunay(points[1, 2, 3]) isn't correct.

What is it that I am doing wrong?

EDIT:

If it's easier to handle, I can also use this line to import (np arrays should be of same type of data?)

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   

Then I would need to skip the first 3 values in each row...

Upvotes: 0

Views: 677

Answers (2)

YS-L
YS-L

Reputation: 14738

The error is with the slicing of numpy array. To get the coordinates of the points, either version of you code is fine.

First version of your code, where the first column of points is a tuple of RGB values:

tri = scipy.spatial.Delaunay(points[:, 1:])

Second version, where the RGB values are flattened, taking up 3 columns, you need to skip three columns:

tri = scipy.spatial.Delaunay(points[:, 3:])

In fact, you can use np.loadtxt for reading in the data (yielding the second version):

points = np.loadtxt('XYZcolorlist_D65.csv')

Upvotes: 1

cohoz
cohoz

Reputation: 760

I'm not sure exactly what you're trying to do, but maybe it's something like this...you can replace file_txt with your csv reader.

>>> from scipy.spatial import Delaunay
>>> file_txt = [[255, 95, 127, 40.2, 26.5, 22.7], [255, 127, 127, 43.6, 32.3, 23.6], [255, 159, 127, 47.1, 39.1, 22.9], [0,0,0,0,0,0]]
>>> a = [list(map(float, row[3:])) for row in file_txt]
>>> a
[[40.2, 26.5, 22.7], [43.6, 32.3, 23.6], [47.1, 39.1, 22.9], [0.0, 0.0, 0.0]]
>>> Delaunay(a)
<scipy.spatial.qhull.Delaunay object at 0x0383FA30>

Upvotes: 0

Related Questions