Created
October 31, 2017 15:13
-
-
Save carsontang/788d2ff2d4ffb1fca51635a46adcd5c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cairo | |
import numpy as np | |
from PIL import Image | |
# imdata is a 2D numpy array of dtype np.uint8 containing grayscale pixel intensities on [0, 255] | |
# repeat for each of R, G, B, and add a deck of 255s for alpha | |
cairo_imdata = np.dstack([imdata, imdata, imdata, np.ones_like(imdata)*255]) | |
surface = cairo.ImageSurface.create_for_data(cairo_imdata, cairo.FORMAT_ARGB32, *(reversed(imdata.shape))) | |
# create a context and do some doodling | |
ctx = cairo.Context(surface) | |
ctx.set_source_rgb(1.0, 0.0, 0.0) # pure red | |
ctx.set_line_width(3) | |
# draw an arc centered at (10,10) with radius 5, from 0 to 2*pi radians | |
ctx.arc(10, 10, 5, 0, 2*np.pi) | |
ctx.stroke() | |
h, w = cairo_imdata.shape[:-1] | |
pil_image = Image.frombuffer("RGBA", (w, h), surface.get_data(), "raw", "BGRA", 0, 1) | |
# now you can do PIL things | |
pil_image.save("image.jpg") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment