Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert PyCairo surface to OpenCV numpy and back in Python 3

I would like to convert OpenCV image to PyCairo, make some manipulations (drawing etc.) and convert it back to OpenCV. Do you know how to do it? Simple examples would be enough. Thank you.

like image 452
Vladyslav Moisieienkov Avatar asked Jul 03 '19 12:07

Vladyslav Moisieienkov


1 Answers

As specified in PyCairo's test code, converting a cairo.ImageSurface object to numpy array:

import cairo
import numpy as np

w = 300
h = 300

surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, w, h)
ctx = cairo.Context (surface)

# Draw out the triangle using absolute coordinates
ctx.move_to (w/2, h/3)
ctx.line_to (2*w/3, 2*h/3)
ctx.rel_line_to (-1*w/3, 0)
ctx.close_path()
ctx.set_source_rgb (0, 0, 0)  # black
ctx.set_line_width(15)
ctx.stroke()

buf = surface.get_data()
array = np.ndarray (shape=(w,h,4), dtype=np.uint8, buffer=buf)
like image 53
WcW Avatar answered Nov 11 '22 08:11

WcW