Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 300
High schooler Avatar asked Oct 10 '13 21:10

High schooler


People also ask

How do I convert an image to pygame surface?

Step 1: First, import the libraries Image and Pygame. Step 2: Now, take the colors as input that you want to use in the game. Step 3: Then, construct the GUI game. Step 4: Further, set the dimensions of your GUI game.

Can pygame handle image formats?

The drawing functions are fine if you want to draw simple shapes on the screen, but many games have images (also called sprites). Pygame is able to load images onto Surface objects from PNG, JPG, GIF, and BMP image files.

What is convert () in pygame?

pygame.Surface.convert. — change the pixel format of an image.


1 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
like image 81
Igonato Avatar answered Oct 13 '22 08:10

Igonato