如何将 PyCairo 表面转换为 OpenCV numpy 并返回 Python 3

Vla*_*kov 5 opencv pycairo python-3.x

我想将 OpenCV 图像转换为 PyCairo,进行一些操作(绘图等)并将其转换回 OpenCV。你知道怎么做吗?简单的例子就足够了。谢谢你。

WcW*_*WcW 5

按照 PyCairo 的测试代码中的规定,将cairo.ImageSurface对象转换为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)
Run Code Online (Sandbox Code Playgroud)

  • 您遇到了一个错误:“w”和“h”在“shape=(w,h,4)”中交换了。我现在已经修好了 (2认同)