5

I found this functions from SciKit-Image which lets you draw normal or anti-aliased lines into an numpy array. There is also the option to create polygons, but these are not anti-aliased

Because there is no function to draw thick lines (width greater than one pixel), I thought about drawing a polygon and on the edges also the lines, to have the anti-aliasing effect. But i think that this isn't the beste solution.

That's why I wanted to ask, if there is a better option to draw thick anti-aliased lines into an numpy array (maybe with matplotlib or sth.)?

vtni
  • 950
  • 3
  • 14
  • 43

2 Answers2

7

With PIL, you can anti-alias by supersampling. For example,

import numpy as np
from PIL import Image
from PIL import ImageDraw

scale = 2
width, height = 300, 200

img = Image.new('L', (width, height), 0)  
draw = ImageDraw.Draw(img)
draw.line([(50, 50), (250, 150)], fill=255, width=10)
img = img.resize((width//scale, height//scale), Image.ANTIALIAS)
img.save('/tmp/antialiased.png')
antialiased = np.asarray(img)
print(antialiased[25:35, 25:35])
# [[252 251 250 255 255 237 127  18   0   0]
#  [255 251 253 254 251 255 255 237 127  18]
#  [184 255 255 254 252 254 251 255 255 237]
#  [  0  72 184 255 255 254 252 254 251 255]
#  [  1   0   0  72 184 255 255 254 252 254]
#  [  0   3   1   0   0  72 184 255 255 254]
#  [  0   0   0   3   1   0   0  72 184 255]
#  [  0   0   0   0   0   3   1   0   0  72]
#  [  0   0   0   0   0   0   0   3   1   0]
#  [  0   0   0   0   0   0   0   0   0   3]]

img = Image.new('L', (width//scale, height//scale), 0)  
draw = ImageDraw.Draw(img)
draw.line([(25, 25), (125, 75)], fill=255, width=5)
img.save('/tmp/aliased.png')
aliased = np.asarray(img)
print(aliased[25:35, 25:35])
# [[255 255 255 255 255 255 255   0   0   0]
#  [255 255 255 255 255 255 255 255 255   0]
#  [255 255 255 255 255 255 255 255 255 255]
#  [  0   0 255 255 255 255 255 255 255 255]
#  [  0   0   0   0 255 255 255 255 255 255]
#  [  0   0   0   0   0   0 255 255 255 255]
#  [  0   0   0   0   0   0   0   0 255 255]
#  [  0   0   0   0   0   0   0   0   0   0]
#  [  0   0   0   0   0   0   0   0   0   0]
#  [  0   0   0   0   0   0   0   0   0   0]]

antialiased.png:

enter image description here

aliased.png

enter image description here

martineau
  • 119,623
  • 25
  • 170
  • 301
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

In the following question someone gave already an option, how to implement it only using numpy.

https://stackoverflow.com/a/47381058

ced-mos
  • 178
  • 1
  • 8