user3048747
user3048747

Reputation: 309

tuples of RGB colors to surfarray in Pygame

I have some array of complex numbers z, which I want to convert to rgb values with function ncol. Then I want to use it to create pygame syrfarray. Here example

import numpy as np
import cmath
z =  np.array([[(complex(-(x/2),-(y/2))) for x in range(2)]for y in range(2)])
def ncol(z):
    if cmath.phase(z)>180:
        w = (255,255,255)
    else:
        w = (125,125,0)
    return w
fz = np.frompyfunc(ncol,1,1)
w = fz(z)
print(w)

How could I translate it to surfarray of pygame? I tried

pygame.surfarray.blit_array(surf,w)

But it gives

ValueError: Unsupported array element type

As I understand z has shape (2,2) and right shape for surfarray have to be (2,2,3)

Answer given by skrx

w = np.array([list(arr) for arr in w])

Upvotes: 2

Views: 870

Answers (2)

skrx
skrx

Reputation: 20438

Try to rearrange your array in this way and then either use pygame.surfarray.make_surface or pygame.surfarray.blit_array.

import numpy as np
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()

z = np.array([
    [(255, 170, 0), (255, 170, 0)],
    [(255, 170, 0), (0, 127, 255)],
    [(255, 170, 0), (255, 170, 0)],
    ])
print(z.shape)
# Either use `make_surface` to create a new surface ...
surface = pg.surfarray.make_surface(z)
# or create the surface first and then use `blit_array` to fill it.
surface2 = pg.Surface(z.shape[:2])
pg.surfarray.blit_array(surface2, z)
done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True

    screen.fill((30, 30, 30))
    screen.blit(surface, (50, 50))
    screen.blit(surface2, (50, 100))

    pg.display.flip()
    clock.tick(30)

Upvotes: 2

M472
M472

Reputation: 330

The shape of your array has to match the size of your surface. This means if you look at the output of numpy.array(z).shape the output has to be (width, height, 3) to the size of your surface. You can check the width and height of your surface using surf.get_width and surf.get_height.

Furthermore the third element of the shape tuple has to be 3 because the surface uses a 3-Tuple to represent the RGB color values.

Upvotes: 3

Related Questions