High schooler
High schooler

Reputation: 1680

OpenCV cv2 image to PyGame image?

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

Upvotes: 11

Views: 9206

Answers (2)

Tom Kuntz
Tom Kuntz

Reputation: 65

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")

Upvotes: 1

Igonato
Igonato

Reputation: 10787

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

Upvotes: 8

Related Questions