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
shapeattribute of anumpy.arrayis 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.Surfacecan be generated bypygame.image.frombuffer. The 1st argument can be anumpy.arrayand the second argument is the format (RGBorRGBA).Get the size (width, height) for the
pygame.Surfaceobject by slicing:Determine the target format for the
pygame.Surfaceobject, 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.reshapeand the gray channel must be expanded to a red-green and blue color channel usingnumpy.repeat:With his data the
pygame.Surfaceobject 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
convertorconvert_alpha:Complete function
cvImageToSurface:Minimal example: