I created images from OpenCV/opencv-python (numpy.array
) and I want to convert them to a pygame.Surface
object:
def cvImageToSurface(cv2Image):
pygameSurface = # ? create from "cvImage"
return pygameSurface
surface = cvImageToSurface(cv2Image)
Some of the images have three channels (BGR) and some of the images also have an alpha channel (BGRA). What do I have to do in cvImageToSurface
to convert images with one of the formats into a pygame.Surface
object?
The
shape
attribute of anumpy.array
is the number of elements in each dimension. The first element is the height, the second the width and the third the number of channels. Apygame.Surface
can be generated bypygame.image.frombuffer
. The 1st argument can be anumpy.array
and the second argument is the format (RGB
orRGBA
).Get the size (width, height) for the
pygame.Surface
object by slicing:Determine the target format for the
pygame.Surface
object, depending on the third channel:Since the source format is BGR or BGRA, but the target format is RGB or RGBA, the red and blue channels have to be swapped:
In the case of a grayscale image, the shape of the array must be changed using
numpy.reshape
and the gray channel must be expanded to a red-green and blue color channel usingnumpy.repeat
:With his data the
pygame.Surface
object can be generated bypygame.image.frombuffer
:To ensure that the image has the same pixel format as the display Surface and for optimal performance, the Surface should be converted with either
convert
orconvert_alpha
:Complete function
cvImageToSurface
:Minimal example: