13

I have a python list of points (x/y coordinates):

   [(200, 245), (344, 248), (125, 34), ...]

It represents a contour on a 2d plane. I would like to use some numpy/scipy algorithms for smoothing, interpolation etc. They normally require numpy array as input. For example scipy.ndimage.interpolation.zoom.

What is the simplest way to get the right numpy array from my list of points?

EDIT: I added the word "image" to my question, hope it is clear now, I am really sorry, if it was somehow misleading. Example of what I meant (points to binary image array).

Input:

[(0, 0), (2, 0), (2, 1)]

Output:

[[0, 0, 1],
 [1, 0, 1]]

Rounding the accepted answer here is the working sample:

import numpy as np

coordinates = [(0, 0), (2, 0), (2, 1)]

x, y = [i[0] for i in coordinates], [i[1] for i in coordinates]
max_x, max_y = max(x), max(y)

image = np.zeros((max_y + 1, max_x + 1))

for i in range(len(coordinates)):
    image[max_y - y[i], x[i]] = 1
2
  • numpy.array(your_list) is probably a good start...? Commented Oct 1, 2012 at 9:39
  • not much of a start... but really what means represent anyways... Commented Oct 1, 2012 at 9:55

3 Answers 3

10

Ah, better now, so you do have all the points you want to fill... then its very simple:

image = np.zeros((max_x, max_y))
image[coordinates] = 1

You could create an array first, but its not necessary.

Sign up to request clarification or add additional context in comments.

1 Comment

@Alex, well you probably had to know that zoom work on images... Btw. forgot to set the datatype (np.zeros((max_x, max_y), dtype=bool)), though if you want to zoom, maybe no point.
0

Building on what Jon Clements and Dunes said, after doing

new_array = numpy.array([(200, 245), (344, 248), (125, 34), ...])

you will get a two-dimensional array where the first column contains the x coordinates and the second column contains the y coordinates. The array can be further split into separate x and y arrays like this:

x_coords = new_array[:,0]
y_coords = new_array[:,1]

2 Comments

... or directly as (x_coords, y_coords)=new_array.T where .T is a shortcut to the .transpose() method.
Rigt, Pierre GM. I almost mentioned that since it's my preferred way as it uses fewer commands. I decided what I wrote was maybe simpler from a conceptual standpoint. The more examples the merrier, though.
-1
numpy.array(your_list)

numpy has very extensive documentation that you should try reading. You can find it online or by typing help(obj_you_want_help_with) (eg. help(numpy)) on the REPL.

1 Comment

I am sorry but how can this help me? I said that I need a numpy array that I can use as input for scipy functions and gave an example (zoom).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.