Alex
Alex

Reputation: 1274

How to convert python list of points to numpy image array?

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

Upvotes: 13

Views: 16517

Answers (3)

seberg
seberg

Reputation: 8975

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.

Upvotes: 10

Michelle Lynn Gill
Michelle Lynn Gill

Reputation: 1154

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]

Upvotes: 0

Dunes
Dunes

Reputation: 40693

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.

Upvotes: 0

Related Questions