7

I've been searching far and wide, but I haven't found a solution yet, so I'll ask here. I have a script that creates a large numpy array of coordinate points (~10^8 points), and i then want to draw a polygonal line using the coordinates. PIL's ImageDraw.line works fine for regular lists, but there seems to be a problem when using numpy arrays.

Right now this is my solution:

image = Image.new('RGB', (2**12, 2**12), 'black')
draw = ImageDraw.Draw(image, 'RGB')
draw.line(pos.tolist(), fill = '#00ff00')

where pos is the large numpy array that contains all points in the following order: [x0, y0, x1, y1, ...] (this can be changed if needed). The most time consuming part of the program is the pos.tolist() part, taking up about 75% of runtime.

Is there a way to draw a line and save it to an image and keeping it as a numpy array? I just want a simple image, nothing else besides the line and the black background.

maxb
  • 625
  • 6
  • 15
  • See [How can I draw lines into numpy arrays?](http://stackoverflow.com/q/31638651/562769) – Martin Thoma Jul 28 '15 at 09:57
  • Have you already thought of simplifying the line before drawing? Maybe a simple decimation (obviously considering the (x0,y0,x1,y1...) format) by 10 or 100 would speed up a lot your routine – lgsp Nov 11 '21 at 09:45

1 Answers1

1

The list cast can be replaced with a float32 cast as follows

draw.line(pos.astype(np.float32), fill='#00ff00')

And you can get rid of casts in general if, when forming an array of points, you explicitly specify the type as np.float32 for the array of points itself and all arrays with which it interacts, for example

pos = np.ones((2**8, 2), dtype=np.float32).reshape(-1)
pos *= np.random.randint(0, 2**12-1, size=(2**8, 2)).reshape(-1)
image = Image.new('RGB', (2**12, 2**12), 'black')
draw = ImageDraw.Draw(image, 'RGB')
draw.line(pos, fill='#00ff00')

should work fine.

  • 1
    I appreciate the effort made in answering a question I asked 8 years ago. Though I must admit that I'm not actively working with this code anymore. – maxb Jan 27 '23 at 12:31