Skip to content

Get PNG as np array? #119

Answered by cduck
lcgd240 asked this question in Q&A
Feb 26, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

Yes, you can use any Python library that can load PNG images like this: imread(d.rasterize().png_data)

Here's a demo:

import drawsvg as draw
from imageio.v3 import imread, imwrite
from io import BytesIO

# Helper function
def display_array(img_array):
    '''Displays a numpy array as an image in Jupyter.'''
    with BytesIO() as f:
        imwrite(f, img_array, extension='.png')
        f.seek(0)
        return draw.Raster(f.read())
# Make your drawing
d = draw.Drawing(100, 100)
d.append(draw.Circle(50, 50, 40, fill='red'))

d

# Convert your drawing into a numpy array
# The array shape is (height, width, 3) if opaque else (height, width, 4)
png_data = d.rasterize().png_data
img_array = i…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@lcgd240
Comment options

Answer selected by cduck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants