from PIL import ImageGrab
import numpy as np
pg.init()
gl_version = (3, 3) # GL Version number (Major, Minor)
pg.display.gl_set_attribute(pg.GL_CONTEXT_MAJOR_VERSION, gl_version[0])
pg.display.gl_set_attribute(pg.GL_CONTEXT_MINOR_VERSION, gl_version[1])
pg.display.gl_set_attribute(pg.GL_CONTEXT_PROFILE_MASK, pg.GL_CONTEXT_PROFILE_CORE)
display_size = (1440, 720)
pg.display.set_mode(display_size, pg.OPENGL | pg.DOUBLEBUF | pg.RESIZABLE)
screen_info = pg.display.Info()
screen_width, screen_height = screen_info.current_w, screen_info.current_h
window_x, window_y = (screen_width - display_size[0])/2, (screen_height - display_size[1])/2 #for recording screen
record_screen = True#False#
if record_screen:
fourcc = cv2.VideoWriter_fourcc(*'XVID')
window_out = cv2.VideoWriter('window_output.avi', fourcc, 30.0, display_size)
if record_screen:
if window_out is not None:
image = ImageGrab.grab(bbox=(window_x, window_y, window_x+display_size[0], window_y+display_size[1]))
#image.save('screenshot.png')
image = np.array(image)
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
window_out.write(image_bgr)
if record_screen:
window_out.release()
这段代码使用Pygame和OpenCV在屏幕上创建一个OpenGL窗口,并记录窗口的内容为视频。
首先,它初始化了Pygame库:
pg.init()
然后,设置OpenGL的版本和配置:
gl_version = (3, 3) # 设置OpenGL版本号为3.3 pg.display.gl_set_attribute(pg.GL_CONTEXT_MAJOR_VERSION, gl_version[0]) pg.display.gl_set_attribute(pg.GL_CONTEXT_MINOR_VERSION, gl_version[1]) pg.display.gl_set_attribute(pg.GL_CONTEXT_PROFILE_MASK, pg.GL_CONTEXT_PROFILE_CORE)
接下来,设置窗口的大小和一些Pygame的窗口属性:
display_size = (1440, 720) # 设置窗口大小为1440x720 pg.display.set_mode(display_size, pg.OPENGL | pg.DOUBLEBUF | pg.RESIZABLE) # 设置窗口模式为OpenGL、双缓冲和可调整大小
然后,获取屏幕信息,计算窗口的位置:
screen_info = pg.display.Info() screen_width, screen_height = screen_info.current_w, screen_info.current_h window_x, window_y = (screen_width - display_size[0])/2, (screen_height - display_size[1])/2 # 计算窗口的位置
接下来,如果设置了record_screen
为True
,则创建一个视频写入器以记录窗口的内容:
record_screen = True if record_screen: fourcc = cv2.VideoWriter_fourcc(*'XVID') # 使用XVID编解码器 window_out = cv2.VideoWriter('window_output.avi', fourcc, 30.0, display_size) # 创建视频写入器
然后,如果需要记录屏幕,就获取窗口的截图,并将其转换为OpenCV可以处理的格式:
if record_screen: if window_out is not None: image = ImageGrab.grab(bbox=(window_x, window_y, window_x+display_size[0], window_y+display_size[1])) # 获取窗口的截图 image = np.array(image) # 将截图转换为NumPy数组 image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # 将RGB格式转换为BGR格式(OpenCV默认的颜色顺序) window_out.write(image_bgr) # 将截图写入视频
最后,如果需要记录屏幕,则释放视频写入器:
if record_screen: window_out.release() # 释放视频写入器
这样,就完成了创建OpenGL窗口并记录窗口内容的整个过程。