Mary
Mary

Reputation: 43

Creating a window in pygame without displaying it

I create a screen in pygame using:

screen = pygame.display.set_mode((width,height))

Then I draw 200 random gray scale circles on it and save the screen as an image. (I need to save this screen as an image so I can compare it to a target image later on):

pygame.image.save(screen, "Circles.png")

Now, I need to randomly change different parameters of different circles by putting the numpy array that contains the circle parameters for all the circles in a loop with a big number as its iteration value.

And I need to redraw the mutated circles on a screen (at the end of each iteration) and save that screen as a png image again.

Now the problem is, every time I use pygame.display.set_mode((width,height)) it opens up the display window and it significantly slows down my program.

I would like to create a screen and save it in a variable but don't need to display that screen at each iteration. I haven't been able to figure out what command to use to avoid displaying the screen.

I appreciate your help.

Upvotes: 4

Views: 2811

Answers (3)

damp11113
damp11113

Reputation: 51

you can use pygame.surfarray.array3d to screenshot it (this can convert to opencv using cv2.cvtColor) and use pygame.image.save to save image but you need to remove pygame.display.set_mode and use pygame.Surface for create virtual screen

import pygame
import cv2
import numpy as np

pygame.init()

def circle_logic(screen):
    # your logic here
    pass
    
virtual_screen = pygame.Surface((500,500))

count = 0

while True:
    ws = circle_drawing(virtual_screen.copy())
    # screenshot
    screenshot = pygame.surfarray.array3d(virtual_screen)
    # save image to file
    pygame.image.save(virtual_screen, "circles_" + str(count)+".png")
    # convert to opencv (optional)
    screenshot_cv = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)

    count +=1

Upvotes: 0

oxrock
oxrock

Reputation: 641

I would probably end up using something like this. This will still popup a screen but it will be tiny and never updated.

import pygame
from pygame.locals import *

pygame.init()

def circle_drawing(surf):
    pass
    #your circle drawing function using passed in surface

DISPLAY = (1, 1)
DEPTH = 32
FLAGS = 0
screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
work_surface  = pygame.Surface((500,500))
count = 0
while True:
    ws = circle_drawing(work_surface.copy())
    pygame.image.save(ws, "circles_" + str(count)+".png")
    count +=1

Upvotes: 1

user2746752
user2746752

Reputation: 1088

If you don't want a window to appear, try creating the surface like this:

screen = pygame.Surface((width,height))

Then you can draw your circles on this surface and save it the same way as you did before. As others have said, clear the surface with the fill() method.

Upvotes: 4

Related Questions