Pycairo get_data() not working with create_for_rectangle()

25 Views Asked by At

I have a function that cuts out a shape from an RGBA image by turning the image into a pycairo surface, cutting out the shape from the surface, and then transferring that into a different pycairo surface.

This works properly, as I have tried saving to png to check the images. However, I'd like to use the image in the new pycairo surface as an array.

This is what I tried to do to achieve that:

surface2 = surface.create_for_rectangle(x_min*scale,y_min*scale,width,height)
buf = surface2.get_data()
crop = np.ndarray(shape = (math.ceil(height),math.ceil(width),4), dtype = np.uint8, buffer=buf)
return crop

This solution was taken from official pycairo documentation. This would work properly for surface, but not with surface2. I assumed it had something to do with the create_for_rectangle() function. The other solution I thought of is writing surface2 to png and then using cv2.imread() to get it, but that seems crude.

1

There are 1 best solutions below

0
Hershel On

I'm not able to find an answer to create_for_rectangle()'s interaction with get_data(). As a solution for what I intend to do however, I did this instead:

surface2 = cairo.ImageSurface(cairo.FORMAT_ARGB32, round(width), round(height))
ctx2 = cairo.Context(surface2)
ctx2.set_source_surface(surface, -x_min*scale, -y_min*scale)
ctx2.paint()

surface2 now works as intended with get_data(), and I am now able to properly get the numpy array associated with surface2.