in data_process.py [0:0]
def vector_to_raster(vector_images, part_label=False, nodetail=False, side=64, line_diameter=16, padding=16, bg_color=(1,1,1), fg_color=(0,0,0)):
"""
padding and line_diameter are relative to the original 512x512 image.
"""
original_side = 512.
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, side, side)
ctx = cairo.Context(surface)
ctx.set_antialias(cairo.ANTIALIAS_BEST)
ctx.set_line_cap(cairo.LINE_CAP_ROUND)
ctx.set_line_join(cairo.LINE_JOIN_ROUND)
ctx.set_line_width(line_diameter)
# scale to match the new size
# add padding at the edges for the line_diameter
# and add additional padding to account for antialiasing
total_padding = padding * 2. + line_diameter
new_scale = float(side) / float(original_side + total_padding)
ctx.scale(new_scale, new_scale)
ctx.translate(total_padding / 2., total_padding / 2.)
raster_images = []
for i, vector_data in enumerate(vector_images):
# clear background
ctx.set_source_rgb(*bg_color)
ctx.paint()
vector_image = []
x_max = y_max = 0
for step in vector_data['all_strokes']:
vector_image.append([]) # for each step
for stroke in step:
if len(stroke) == 0: # skip the empty stroke
vector_image[-1].append([])
continue
vector_image[-1].append(np.array([stroke[0][:2]]+[point[2:4] for point in stroke])) # add each stroke N x 2
x_max_stroke, y_max_stroke = np.max(vector_image[-1][-1], 0)
x_max = x_max_stroke if x_max_stroke>x_max else x_max
y_max = y_max_stroke if y_max_stroke>y_max else y_max
offset = ((original_side, original_side) - np.array([x_max, y_max])) / 2.
offset = offset.reshape(1,2)
for j in range(len(vector_image)):
for k in range(len(vector_image[j])):
vector_image[j][k] = vector_image[j][k]+offset if len(vector_image[j][k]) > 0 else vector_image[j][k]
# draw strokes, this is the most cpu-intensive part
ctx.set_source_rgb(*fg_color)
for j, step in enumerate(vector_image):
if part_label:
ctx.set_source_rgb(*COLORS[vector_data['partsUsed'][j]])
if nodetail and j == len(vector_image)-1 and vector_data['partsUsed'][j] == 'details':
continue
for stroke in step:
if len(stroke) == 0:
continue
ctx.move_to(stroke[0][0], stroke[0][1])
for x, y in stroke:
ctx.line_to(x, y)
ctx.stroke()
surface_data = surface.get_data()
if part_label:
raster_image = np.copy(np.asarray(surface_data)).reshape(side, side, 4)[:, :, :3]
else:
raster_image = np.copy(np.asarray(surface_data))[::4].reshape(side, side)
raster_images.append(raster_image)
return raster_images