OpenCV cv2 image to PyGame image?

Question:

def cvimage_to_pygame(image):
    """Convert cvimage into a pygame image"""
    return pygame.image.frombuffer(image.tostring(), image.shape[:2],
                                   "RGB")

The function takes a numpy array taken from the cv2 camera. When I display the returned pyGame image on a pyGame window, it appears in three broken images. I don’t know why this is!

Any help would be greatly appreciated.

Heres what happens::

(Pygame on the left)

enter image description here

Asked By: High schooler

||

Answers:

In the shape field width and height parameters are swapped. Replace argument:

image.shape[:2] # gives you (height, width) tuple

With

image.shape[1::-1] # gives you (width, height) tuple
Answered By: Igonato

An other issue that i found : Colors are not right… This is because open cv images are in BGR (Blue Green Red) not in RGB ! so the right command is :

pygame.image.frombuffer(image.tostring(), image.shape[1::-1], "BGR")
Answered By: Tom Kuntz
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.